Tech Interview RoomStudy guides

HTML & CSS

How does specificity work? Explain the cascade, layers and !important.

Intermediate · 2 min read · Lesson 4 of 7 in HTML & CSS

When several rules set the same property on an element, the cascade picks one, in this order:

  1. Origin and importance: user-agent, user and author styles, with !important reversing the order.
  2. Cascade layers (@layer): later layers beat earlier ones; unlayered styles beat all layers.
  3. Specificity.
  4. Order of appearance: the later rule wins.

Specificity

Counted as three numbers (A, B, C):

  • A: ID selectors (#nav).
  • B: classes, attributes, pseudo-classes (.btn, [type=text], :hover).
  • C: elements and pseudo-elements (a, ::before).

#nav .link is (1,1,0) and beats .nav .link.active (0,3,0). Inline style beats all selectors. :where() adds zero specificity, :is() and :not() take their most specific argument.

Practical advice

  • Keep specificity low and flat (one class per selector, as in BEM or utility CSS).
  • Use @layer reset, base, components, utilities; so ordering, not selector tricks, decides priority.
  • Avoid !important except for utilities that must always win.

Example

css
@layer reset, components, utilities;

@layer components {
  .btn { background: navy; color: white; }
  .card .btn { background: teal; }            /* (0,2,0) */
}
@layer utilities {
  .bg-red { background: crimson; }            /* wins over components: later layer */
}

:where(.prose) a { color: inherit; }          /* specificity (0,0,1): easy to override */

Follow-up questions interviewers ask

Try answering each one before you open it.

How do CSS Modules, Vue scoped styles and Tailwind avoid specificity wars?

CSS Modules hash class names per file, so selectors never collide. Vue <style scoped> adds a unique data attribute to the component's elements and selectors. Tailwind uses single-class utilities with equal specificity, ordered by its layers. All three keep selectors flat, which is the real cure.