Fossils🧠 ConceptualExplain CSS Specificity
ðŸĨšEggCSSFundamentals

Explain CSS Specificity

Specificity determines which CSS rules win. Senior engineers reason about it in terms of maintenance, not just math.

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):

ComponentSelector TypeExample
aID selectors#header
bClass, attribute, pseudo-class.nav, [type="text"], :hover
cElement, pseudo-elementdiv, ::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

  1. Inline styles beat everything except !important
  2. !important overrides all specificity — and creates unmaintainable CSS
  3. :where() has zero specificity — great for default styles
  4. :is() takes the specificity of its most specific argument
  5. @layer allows 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
  • !important is 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.