Chapter 2. Understanding the Cascade

There’s nothing worse than writing a bunch of CSS only to test it out and find that other styles are being applied instead of the ones you intended. To better understand why this happens, this chapter explains how web browsers determine which styles to apply to which elements using the cascade.

What Is the Cascade?

The cascade is the method by which the browser determines how styles should be applied to elements. Because multiple styles can be applied to the same element, understanding how the cascade works is important in the event that styles are not applied they way you expect them to be. Luckily, it’s not as complicated as it sounds; styles are applied based on the specificity of their selectors as well as the order in which they appear.

Selector Specificity

Specificity is a measure of how precisely elements are identified based on the CSS selectors used. Specificity is calculated by analyzing the different types of selectors (except the universal selector, *) that are combined to select an element. A specificity is determined by plugging numbers into (a, b, c, d):

  1. If the styles are applied via the style attribute, a=1; otherwise, a=0.

  2. b is equal to the number of ID selectors present.

  3. c is equal to the number of class selectors, attribute selectors, and pseudoclasses present.

  4. d is equal to the number of type selectors and pseudoelements present.

When all of these calculations are completed, those numbers are concatenated to ...

Get CSS Refactoring now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.