CSS Specificity: How Styles Actually Win

Specificity rules, common traps, and practical strategies to avoid fighting CSS.

F

Frontend Interview Team

February 08, 2026

2 min read
CSS Specificity: How Styles Actually Win

30‑second interview answer

Specificity is how browsers decide which CSS rule wins when multiple rules target the same element. In general: inline styles > IDs > classes/attributes/pseudo-classes > elements/pseudo-elements. If specificity ties, the later rule wins. Avoid specificity wars by using predictable patterns (utility classes, CSS modules, BEM) and keeping selectors simple.


Specificity ladder (memorize this)

From strongest to weakest:

  1. style="..." inline styles
  2. #id
  3. .class, [attr], :hover, :focus, etc.
  4. div, h1, ::before

If two rules have the same specificity, the one later in the stylesheet wins.


Common examples

/* element */
button { color: blue; }
 
/* class beats element */
.btn { color: green; }
 
/* id beats class */
#save { color: red; }

The trap: “Why is my CSS not applying?”

Typical causes:

  • Another rule has higher specificity
  • Same specificity but later rule overrides
  • More specific selector in a component stylesheet
  • !important somewhere upstream

Debugging steps

  1. Inspect element → see which rule is crossed out
  2. Check selector specificity
  3. Search for !important

!important (how to talk about it)

Interview-safe stance:

  • Avoid it for normal styling.
  • Acceptable for:
    • quick emergency hotfix
    • utility overrides in a controlled system
    • third-party style overrides

But if you rely on !important often, it signals poor structure.


Strategies to avoid specificity wars

  1. Keep selectors shallow Bad:
.header .nav ul li a span { ... }

Good:

.navLink { ... }
  1. Use CSS Modules / scoped styles Reduces collisions.

  2. Use utility-first (Tailwind) Avoids cascade surprises.

  3. Use BEM naming Predictable class patterns.


Mini Q&A

Q1: What wins: .btn.primary vs #save?

  • #save (ID).

Q2: If specificity is equal?

  • Later rule wins.

Q3: Should you use !important?

  • Rarely; prefer better structure.

Summary checklist

  • I can state the specificity order.
  • I can debug overrides in DevTools.
  • I keep selectors simple and shallow.
  • I avoid !important unless necessary.