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:
- Importance:
!importantwins over normal declarations (avoid it; it is a debugging tool, not a design tool). - Specificity: the more specific selector wins.
- 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.
| selector | specificity |
|---|---|
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?
- HTML: <p class="note" id="top">Hi</p>
- Rules: p { color: red } (0,0,1), .note { color: blue } (0,1,0), #top { color: green } (1,0,0).
- The id rule has the highest specificity, so the text is green.
<p class="note" id="top">Hi</p>