Explain CSS Specificity
Specificity is the algorithm browsers use to decide which CSS declarations apply when multiple rules target the same element.
The Calculation
Specificity is computed as a tuple (a, b, c):
| Component | Selector Type | Example |
|---|---|---|
| a | ID selectors | #header |
| b | Class, attribute, pseudo-class | .nav, [type="text"], :hover |
| c | Element, pseudo-element | div, ::before |
/* (0, 0, 1) */
p { color: black; }
/* (0, 1, 1) */
p.intro { color: blue; }
/* (1, 0, 1) */
#main p { color: red; }
/* (0, 2, 1) â class beats element count */
.container .intro p { color: green; }The Traps
- Inline styles beat everything except
!important !importantoverrides all specificity â and creates unmaintainable CSS:where()has zero specificity â great for default styles:is()takes the specificity of its most specific argument@layerallows you to control cascade priority independently of specificity
The Senior Answer
Don't just explain the math. Explain the engineering implications:
- High-specificity selectors create coupling and make refactoring painful
!importantis technical debt â it breaks the cascade- Modern CSS (cascade layers,
:where()) gives us tools to manage specificity at scale - BEM, utility-first CSS, and CSS Modules all solve specificity by avoiding it
The best CSS architecture makes specificity irrelevant by keeping selectors flat and predictable.