CSS · Unit 2: The box model · Lesson 5 of 5
The cascade and specificity
When two rules set the same property on an element, the more specific selector wins.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
When two rules set the same property on an element, the more specific selector wins. An id beats a class, and a class beats an element name.
When they are equally specific, the rule that comes later wins. That is the cascade.
Keep specificity low: style with classes, avoid ids for styling and avoid !important. Low specificity keeps rules easy to override later.
Worked example
CSS
p {
color: black;
}
.alert {
color: crimson;
}
p {
font-weight: bold;
}
The HTML it styles
<p class="alert">Check your email.</p>
The text is crimson because .alert is more specific than p. It is also bold, because nothing else sets font-weight.
Key terms
- Cascade
- When rules are equally specific, the later one wins.
- Specificity
- How strongly a selector targets: ids beat classes, and classes beat element names.
Practise it in Code Academy
It has 4 exercises (predict the output, fix the broken code and multiple choice) and takes about 8 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.