Selectors and the Cascade
You style the bakery's prices brown, then find one price stubbornly showing green. Somewhere, another rule is also targeting it, and CSS has to decide which rule wins. Once you know how it decides, these puzzles take seconds instead of an afternoon.
The rule
More specific wins; on a tie, the later rule wins.
A CSS rule is a selector plus declarations:
.price {
color: saddlebrown;
font-weight: bold;
}.price is the selector (which elements), and each property: value; line is a declaration (what to change).
The selectors you will use most:
| Selector | Matches |
|---|---|
p |
every <p> element (type selector) |
.price |
every element with class="price" |
#order-form |
the element with id="order-form" |
.card p |
any <p> somewhere inside a .card (descendant) |
.card > p |
a <p> that is a direct child of a .card |
a:hover |
a link while the pointer is over it (pseudo-class) |
h1, h2 |
both h1 and h2 (a list) |
The cascade is how conflicts are settled when several rules set the same property on the same element:
- Importance and origin: a declaration marked
!importantbeats normal ones. Treat this as a last resort. - Specificity: count the selector's parts as a score of three columns: ids, then classes (and attributes and pseudo-classes), then types. Compare column by column from the left.
- Order: if the scores tie, the rule that appears later wins.
Styles written straight into an element's style="..." attribute beat any selector in a stylesheet.
Inheritance is a separate idea: some properties, mostly text ones like color and font-family, pass down from parent to child when the child has no value of its own. Box properties such as border and padding do not.
The shortcut
Write each selector's score as (ids, classes, types) and compare left to right, like comparing version numbers. (0,1,0) beats (0,0,5), because a single class outranks any number of types.
Find the rules
.card .price { color: green; }and.price { color: saddlebrown; }both target the price.
The trap is fixing a lost fight by adding !important or an id. Each fix raises the stakes for the next rule, until the stylesheet becomes a stack of overrides.
Drills
Answer fast — trust the rule.
What is the specificity score of #menu .item a?
Both rules are .price { ... } with different colours, one at line 10 and one at line 40. Which colour shows?
Which wins for a paragraph with class="note": div div div p or .note?
The .card has color: brown and border: 1px solid tan. The <p> inside has no styles of its own. What does it get?
Remember
- More specific wins; on a tie, the later rule wins.
- Score as (ids, classes, types) and compare from the left.
- Trap: winning fights with
!importantor ids makes every later change harder.
