Selectors, Specificity & the Cascade
Understand how browsers resolve conflicting CSS rules using origin, specificity, source order, inheritance, and @layer.
What you'll learn
- Predict which CSS rule wins using specificity (ID > Class > Element)
- Understand which properties inherit (like color and font-family) vs. which don't
- Avoid !important wars by keeping selector specificity low
CSS stands for Cascading Style Sheets. The Cascade is the exact algorithm browsers use to decide which style wins when multiple rules target the same element.
Specificity Hierarchy
Think of specificity as a three-column score (IDs, Classes/Attributes/Pseudo-classes, Elements):
| Selector | Score | Example |
|---|---|---|
| Element | (0, 0, 1) | p, h1, button |
| Class / Attribute / Pseudo-class | (0, 1, 0) | .btn, [type="email"], :hover |
| ID | (1, 0, 0) | #hero |
When two rules have the exact same specificity, the last rule in the stylesheet wins.
.card-title {
color: #1d4ed8;
} #main div.wrapper ul li a.card-title {
color: #1d4ed8 !important;
} Low-specificity class selectors are easy to override later without resorting to !important.
Fill-in-the-Blank Exercise
Selector Syntax Practice
Target all elements with class 'badge', an element with id 'banner', and a button when hovered.
badge { font-weight: 700; }
banner { padding: 16px; }
button { opacity: 0.9; }Try It Yourself
Notice how .highlight beats p, and #winner beats .highlight, even though #winner is written earlier in the CSS!
Check Your Understanding
1. Which selector has the highest specificity?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.