CSS Specificity Explained - How the Cascade Works
Understand CSS specificity: how browsers decide which styles win. Learn the (ID, Class, Element) scoring system, cascade order, !important, and strategies for managing specificity.
Detailed Explanation
Understanding CSS Specificity
Specificity is the algorithm browsers use to determine which CSS declaration applies when multiple rules target the same element. It is one of the three pillars of the CSS cascade (along with importance and source order).
The Specificity Tuple
Specificity is calculated as a three-part tuple: (a, b, c)
| Component | What counts | Examples |
|---|---|---|
| a (ID) | ID selectors | #header, #nav |
| b (Class) | Classes, attributes, pseudo-classes | .btn, [type], :hover |
| c (Element) | Type selectors, pseudo-elements | div, p, ::before |
Comparison Rules
Specificity is compared left to right:
(1, 0, 0) > (0, 99, 99) — One ID beats any number of classes
(0, 1, 0) > (0, 0, 99) — One class beats any number of elements
(0, 2, 0) > (0, 1, 5) — More classes wins
Examples
* → (0, 0, 0)
p → (0, 0, 1)
p.intro → (0, 1, 1)
p.intro.highlight → (0, 2, 1)
#header → (1, 0, 0)
#header .nav li → (1, 1, 1)
#header .nav li.active → (1, 2, 1)
Special Cases
*(universal) — zero specificity:where()— zero specificity (great for defaults):is()/:not()/:has()— specificity of most specific argument- Inline styles — override all selector-based specificity
!important— overrides everything (including inline styles)
Managing Specificity
- Use classes predominantly — consistent specificity (0, 1, 0)
- Avoid IDs for styling — their high specificity creates escalation
- Use
:where()for reset/default styles — zero specificity, easy to override - Use CSS Layers (
@layer) — control cascade order independently of specificity - Follow a methodology — BEM, ITCSS, or utility-first prevent specificity wars
Use Case
Understanding specificity is essential for every CSS developer. Specificity conflicts are the most common source of CSS bugs, and debugging them requires understanding the scoring algorithm. Specificity knowledge helps teams choose CSS architectures (BEM, CSS Modules, utility-first) and write maintainable stylesheets that scale across large applications.