CSS Specificity Explained: Why Your Styles Are Being Overridden
Demystify CSS specificity with clear rules and practical examples. Understand the specificity hierarchy, how to calculate specificity scores, and strategies for writing maintainable selectors.
Key Takeaways
- When multiple CSS rules target the same element, specificity determines which rule wins.
- Count selectors at each level independently.
- Over-qualified selectors**: `div#header` has unnecessarily high specificity. Just `#header` works and is easier to override
- Use classes for styling, IDs for JavaScript hooks
The Specificity Hierarchy
When multiple CSS rules target the same element, specificity determines which rule wins. Understanding specificity eliminates the frustration of styles that mysteriously refuse to apply.
Specificity Scoring
| Level | Selector Type | Score | Example |
|---|---|---|---|
| Highest | Inline styles | 1,0,0,0 | style="color: red" |
| High | ID selectors | 0,1,0,0 | #header |
| Medium | Classes, attributes, pseudo-classes | 0,0,1,0 | .nav, [type=text], :hover |
| Low | Elements, pseudo-elements | 0,0,0,1 | div, ::before |
| None | Universal selector | 0,0,0,0 | * |
How Scoring Works
Count selectors at each level independently. div.nav#main scores (0,1,1,1) — one ID, one class, one element. #main .nav .item scores (0,1,2,0) — one ID, two classes. The first selector wins because IDs outweigh any number of classes.
Common Specificity Problems
- Over-qualified selectors:
div#headerhas unnecessarily high specificity. Just#headerworks and is easier to override - ID selectors in CSS: IDs create specificity bottlenecks. Prefer classes
!importantescalation: Each!importantforces the next override to also use!important, creating an unwinnable arms race
Best Practices
- Use classes for styling, IDs for JavaScript hooks
- Keep specificity flat — single-class selectors (BEM pattern)
- Reserve
!importantfor utility classes only - Use cascade layers (
@layer) for architectural specificity control
Calculate specificity for any selector with the Peasy CSS specificity calculator.