Skip to the workspace
Pebellslearn by building
CSS  ›  Lesson

Selectors and the Cascade

CSS 15 minSelectors choose elements, and when rules conflict the cascade picks the winner by importance, then specificity counted as ids, classes and types, then source order.

frontend / Selectors and the Cascade

Explore each scene at your own pace.

01 · The rule

The rule

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:

  1. Importance and origin: a declaration marked !important beats normal ones. Treat this as a last resort.
  2. 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.
  3. 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.