CSS Specificity Explained 🎯
Why your selector loses and another one wins.
When two rules target the same element, specificity decides who wins. It’s a score, not a guess.
The score: (IDs, classes, elements)
Read specificity as three numbers, highest wins left to right:
- IDs —
#nav→(1,0,0) - Classes, attributes, pseudo-classes —
.btn,[type],:hover→(0,1,0) - Elements & pseudo-elements —
div,::before→(0,0,1)
So #nav .link is (1,1,0) and beats .menu .link a at (0,2,1) — one ID outranks any number of classes.
/* (0,0,1) */
a { color: gray; }
/* (0,1,0) wins over the element rule */
.link { color: blue; }
/* (1,0,0) wins over the class rule */
#nav { color: red; }Tie-breaker
Equal specificity? The rule that appears later in the source wins.
The outliers
- Inline styles (
style="...") beat all selectors. !importantoverrides everything — use it sparingly; it's a maintenance trap.
.link { color: blue !important; } /* hard to override later */TL;DR: Count IDs, then classes, then elements; on a tie, later wins — and avoid !important.
Get Marcelo Domingues’s stories in your inbox
Join Medium for free to get updates from this writer.
Next time a style “won’t apply,” compute both selectors’ scores before touching the CSS.






