Introduction
Cascade and Specificity
When two rules target the same element and set the same property, which one wins? The browser checks three things, in order:
- 1. Importance: a declaration with
!importantbeats normal ones. - 2. Specificity: a more specific selector beats a less specific one.
- 3. Order: if they are equal, the rule written last wins.
Specificity score
| Selector | Example | Strength |
|---|---|---|
| Inline style | style="..." | Strongest |
| ID | #title | Very strong |
| Class, attribute, pseudo-class | .note, [type], :hover | Medium |
| Element, pseudo-element | p, ::before | Weak |
p { color: black; } /* weakest */
.intro { color: blue; } /* beats p */
#hero { color: green; } /* beats .intro */<p id="hero" class="intro">What colour am I?</p>The text is green, because the id selector is the most specific.