🍋
Menu
Best Practice Beginner 1 min read 274 words

CSS Selector Specificity Deep Dive

Master CSS specificity calculation, understand the cascade, and avoid specificity wars in large projects.

Key Takeaways

  • Specificity determines which CSS rule wins when multiple rules target the same element.
  • Misunderstanding specificity leads to the dreaded !important chains and increasingly convoluted selectors.
  • ### !important: When It's Acceptable Use !important only for utility classes that must override any component styles (like `.
  • Never use !important to fix a specificity problem — fix the specificity instead.

CSS Specificity

Specificity determines which CSS rule wins when multiple rules target the same element. Misunderstanding specificity leads to the dreaded !important chains and increasingly convoluted selectors.

The Specificity Algorithm

Specificity is calculated as a tuple of three values: (IDs, Classes, Elements). #nav .link a has specificity (1,1,1). .sidebar .nav-link:hover has specificity (0,3,0). div > p + p has specificity (0,0,3). Higher values win, comparing left to right: (1,0,0) beats (0,99,99).

What Doesn't Affect Specificity

The universal selector (*), combinators (+, >, ~, space), and :where() have zero specificity. :where(.class) has specificity (0,0,0), while :is(.class) has the specificity of its most specific argument. This makes :where() powerful for resettable defaults.

Specificity Wars

Specificity escalation happens when developers override styles by adding more specific selectors, creating a cascade of increasing specificity. This quickly becomes unmaintainable. Solutions: use a methodology like BEM that keeps specificity flat (single class selectors), use CSS custom properties for values that need to vary, and use cascade layers (@layer) to control the override order independently of specificity.

Cascade Layers

CSS @layer provides a new mechanism for controlling cascade order that works independently of specificity. Styles in earlier layers are overridden by styles in later layers, regardless of specificity. This lets utility classes override component styles cleanly: @layer base, components, utilities.

!important: When It's Acceptable

Use !important only for utility classes that must override any component styles (like .hidden { display: none !important }), and for user-preference overrides like forced dark mode. Never use !important to fix a specificity problem — fix the specificity instead. In a well-organized codebase, !important should appear fewer than 10 times.

Alat Terkait

Format Terkait

Panduan Terkait