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.