TutreNews Learn

Rules, selectors and the cascade

The cascade, specificity and inheritance

Goal: Predict which of several competing rules wins · 12 min

When several rules set the same property on one element, the browser must pick one. The "cascade" decides in this order:

  1. Importance: !important wins over normal declarations (avoid it; it is a debugging tool, not a design tool).
  2. Specificity: the more specific selector wins.
  3. Source order: if specificity is equal, the later rule wins.

Specificity is counted as three numbers (ids, classes, types):

  • each #id adds to the first number,
  • each .class, [attribute] and :pseudo-class adds to the second,
  • each type (p, div) and ::pseudo-element adds to the third,
  • inline styles beat all selectors; the universal selector adds nothing.
selectorspecificity
p(0,0,1)
.note(0,1,0)
p.note(0,1,1)
#nav .item a(1,1,1)
a:hover(0,1,1)

Compare left to right: (1,0,0) beats (0,9,9). Counting never "carries over".

Inheritance: some properties pass from parent to child automatically (color, font-family, font-size, line-height, text-align), others do not (border, margin, padding, background, width). Force it with inherit.

Worked example: Who wins?

  1. HTML: <p class="note" id="top">Hi</p>
  2. Rules: p { color: red } (0,0,1), .note { color: blue } (0,1,0), #top { color: green } (1,0,0).
  3. The id rule has the highest specificity, so the text is green.
<p class="note" id="top">Hi</p>