Sub topic 3
The Cascade: Origin, Specificity, and Source Order
Assume you know basic HTML, linked stylesheets, and common CSS properties. The cascade is the process the browser uses when several declarations match the same element.
How the cascade chooses a declaration
The browser compares matching declarations in this order:
- Origin and importance.
- Cascade layer.
- Specificity.
- Source order.
For ordinary author styles, specificity is written as an (ID, class, type) triple. An ID beats any number of classes. A class, attribute selector, or pseudo-class beats any number of type selectors. If the triples tie, the later declaration wins.
p { color: black; } /* (0,0,1) */
.note { color: green; } /* (0,1,0) */
#content p.note { color: blue; } /* (1,1,1) */A paragraph with id="content" and class="note" becomes blue.
Inheritance is considered only when an element has no direct declaration for a property. A direct rule therefore beats a value inherited from a parent.
`!important`
The !important flag changes the priority of a declaration within its origin. It is useful for narrow exceptions, but frequent use makes styles difficult to override and debug.
#alert { color: blue; }
.message { color: red !important; }The text is red. The important declaration beats the normal declaration despite the ID selector.
Functional pseudo-classes
:is(), :not(), and :where() match elements without changing the matched elements themselves. Their specificity differs:
:is()and:not()use the most specific argument.:where()always contributes zero specificity.
:is(.card, #featured) p { color: navy; } /* (1,0,1) */
:where(.card, #featured) p { color: teal; } /* (0,0,1) */
p:not(.hidden) { color: purple; } /* (0,1,1) */Cascade layers
Layers provide an explicit ordering before specificity. For normal declarations, a later layer wins over an earlier layer.
@layer reset, components;
@layer reset {
#nav a { color: black; }
}
@layer components {
a { color: blue; }
}The link is blue because components comes after reset.
Keep specificity manageable
Prefer single-purpose classes such as .button and .button--primary. Keep selectors short. Use :where() for reusable structural selectors when consumers should override them easily. Reserve IDs and !important for exceptional cases.
Debug conflicting styles
In browser developer tools, inspect the element and open the Styles or Computed panel. Crossed-out declarations lost the cascade. Compare their origin, layer, specificity, and source order. The tool usually shows the selector and the file line that supplied the winning value.
Exercise
Which declaration sets the color, and why? #box { color: blue; } .panel { color: red !important; }
Show answer
Red wins because !important beats a normal declaration.