Advanced

The cascade and specificity

When two rules describe the same element, CSS decides which one wins by a score, and that score is why a stylesheet grows harder to reason about the more selectors you use. The way to keep it simple is to write selectors that lose or win predictably, not to outscore them.

What you will see

Still blue, and now the rule states where it applies rather than forcing a win. That is the shape to prefer.

About 2 min of reading

Try It

Predict then check the winner.

1

Two rules, one element

.box { color: red; } #main .box { color: blue; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Blue - the id in the second selector raises its score, so order does not matter.
2

Narrow instead of force

.section .box { color: blue; }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Still blue, and now the rule states where it applies rather than forcing a win. That is the shape to prefer.

Data Flow

Rules are scored and the winner applies.
1 Collect every rule that matches
↓
2 Score each by specificity
↓
3 Break ties by order
↓
4 Apply the winner per property
Why this works
One class per concern

A class that carries layout and a class that carries appearance are different concerns, and mixing them means one cannot change without the other. Naming them separately is what keeps a stylesheet editable after six months.

Reset the defaults you rely on

Browsers bring default styles for headings, lists, and links. Setting the values you actually want at the top of the file makes the page independent of those defaults, which is what makes a design portable.

Examples

Specificity is a count

An id beats a class, a class beats an element name, and the later rule wins on a tie. Knowing the count means you can predict the winner instead of testing it, and it means a rule with an id in it is a rule nothing can override cleanly.

Later loses to more specific

Putting a rule at the bottom of the file does not guarantee it wins. A more specific rule above it still wins, which is why ordering alone is not a strategy and specificity is.

Scope instead of force

The alternative to raising specificity is narrowing the selector, like .card .title instead of a forced value. A narrow selector states where the style applies, which a forced value hides.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Finding why a style is wrong
Previous Lesson
Finding why a style is wrong
Next Lesson
Custom properties and theming
Custom properties and theming →