The cascade and specificity
Why one rule wins over another, and how to stop fighting your own CSS.
When several rules set the same property on an element, the browser picks one with a fixed order. This is the cascade.
- Importance:
!importantbeats normal declarations. - Cascade layers (
@layer): rules in a later layer win over earlier layers. - Specificity: the more specific selector wins.
- Order: if everything else is equal, the rule written last wins.
Specificity
Specificity is counted as three numbers: IDs, then classes (plus attributes and pseudo-classes), then element types.
| Selector | IDs | Classes | Elements |
|---|---|---|---|
p | 0 | 0 | 1 |
.card | 0 | 1 | 0 |
nav a:hover | 0 | 1 | 2 |
#top .menu a | 1 | 1 | 1 |
A selector with one class beats any number of element selectors. An ID beats any number of classes. Inline style beats all of them.
Habits that keep CSS manageable
- Style with classes, not IDs, and keep selectors short (one or two levels).
- Avoid
!important. It forces the next rule to use it too, and leads to a spiral. - Use
:where()to write selectors with zero specificity, which is handy for defaults::where(.prose) a { ... }. - Inspect a rule in DevTools: the Styles pane shows struck-through declarations that lost, and why.
NoteSome properties inherit from the parent (color, font-family) and others do not (margin, border). Use inherit, initial or unset to control it.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.