The CSS Cascade and Specificity: Which Rule Wins
Sooner or later two rules will set the same property on the same element to different values. The cascade is the algorithm that decides which declaration wins. Once you know its steps, "why is my style not applying?" stops being a mystery.
The steps, in order
The browser compares competing declarations using these criteria, moving to the next step only when there is a tie:
- Origin and importance. Your stylesheets beat the browser's built-in defaults. A declaration marked
!importantbeats normal declarations. - Specificity. The more specific selector wins.
- Order of appearance. If everything else is equal, the declaration that comes last wins.
(The full specification also has cascade layers and scoping, which advanced codebases use to organize large stylesheets. You can ignore them until you need them.)
Counting specificity
Specificity is written as three numbers (A, B, C):
- A counts ID selectors.
- B counts classes, attribute selectors and pseudo-classes such as
:hover. - C counts type selectors and pseudo-elements such as
::before.
Compare the numbers from left to right, like versions. #nav a is (1,0,1) and beats .menu .link, which is (0,2,0), because one ID outranks any number of classes. The universal selector * and combinators add nothing. Inline style="" attributes beat all selectors.
See it happen
The example sets one paragraph's color four times. The .intro rule beats the p rule even though it comes first, because (0,1,0) is greater than (0,0,1). .lead ties with .intro and comes later, but the final rule, .intro.lead, has two classes (0,2,0) and wins outright. The script prints the color the browser actually used.
Expected page text
Which color am I? Computed color: rgb(29, 78, 216)
Delete the .intro.lead rule and run it again: the paragraph turns teal, because the remaining class rules are tied on specificity and the last one wins.
About !important
!important jumps the queue, which makes it tempting. The trouble is that the only way to override an important declaration is another important one with equal or higher specificity, and stylesheets that rely on it become a stack of escalating overrides. Use it rarely, for things like utility classes that must always win, and prefer writing a more specific selector or reordering rules.
Debugging tips
- In developer tools, the Styles panel lists every rule that matched, with overridden declarations struck through. The winning one is at the top.
- If a rule "does nothing", check whether a more specific selector elsewhere sets the same property.
- Keep selectors short and mostly class-based. Low, even specificity keeps the source-order rule predictable.
Summary
- The cascade compares importance, then specificity, then source order.
- Specificity is (IDs, classes, types); compare left to right.
- Prefer clear selectors over
!important.
Quiz: Cascade and specificity