Understanding CSS Specificity
Ad
What is Specificity?
When multiple CSS rules target the same element, specificity decides which one wins. Understanding it ends the frustration of "why isn't my CSS applying?"
The Specificity Hierarchy
| Selector type | Weight |
|---|---|
| Inline style | 1000 |
| ID (#id) | 100 |
| Class, attribute, :hover | 10 |
| Element (div, p) | 1 |
Example
p { color: blue; } /* weight 1 */
.text { color: green; } /* weight 10 — wins */
#main { color: red; } /* weight 100 — wins over both */
The Cascade Tiebreaker
If specificity is equal, the last rule wins:
.box { color: blue; }
.box { color: red; } /* red wins — comes later */
Avoid !important
p { color: blue !important; } /* overrides everything — use sparingly */
FAQs
How do I beat a stubborn rule?
Increase specificity (add a class/ID) rather than reaching for !important. More in our CSS section.
Why is !important bad?
It breaks the natural cascade and is hard to override later.
