Sub topic 1
Rules, selectors and declarations: the inputs to the cascade
Prerequisites
You should know basic HTML nesting, classes, and IDs. You should also be able to write simple CSS rules and inspect elements in browser developer tools.
Rules, selectors and declarations
A CSS rule contains a selector and one or more declarations. A selector chooses elements. A declaration pairs a property with a value.
p.note {
color: navy;
margin: 1rem;
}Here, p.note selects paragraphs with the note class. color: navy and margin: 1rem are declarations. The browser considers each declaration separately for each matching element.
Why conflicts happen and what the cascade does
Several rules can match the same element and set the same property. The cascade is the browser's process for choosing one winning declaration.
p {
color: black;
}
.note {
color: blue;
}
#intro {
color: green;
}For <p id="intro" class="note">Hello</p>, all three rules match. The browser compares their precedence instead of using the first matching rule. In this case, the ID selector wins because it has greater specificity.
Origins and `!important`
An origin identifies who supplied a rule: the browser, the user, or the page author. Normal author styles usually beat normal user-agent styles, which are the browser's defaults.
The !important flag changes precedence. Important declarations are considered before normal declarations. Within the same origin, an important declaration can beat a more specific normal declaration.
p {
color: red !important;
}
#intro {
color: green;
}The paragraph is red. Use !important sparingly because it makes later maintenance and overrides harder.
> callout note > Cascade layers add another precedence step between origin and specificity. This chapter uses the basic comparison; later rules must still be checked for layers.
Specificity: counting selector parts
Specificity measures how narrowly a selector targets elements. Compare the counts as (IDs, classes, elements):
| Selector | Specificity |
|---|---|
| `#intro` | `(1, 0, 0)` |
| `.note` | `(0, 1, 0)` |
| `p` | `(0, 0, 1)` |
An ID beats any number of classes in the usual comparison. A class beats an element selector. If specificity ties, source order decides the winner.
Exercise
Which rule colors <p id="intro" class="note">Hi</p> green?
Show answer
#intro { color: green; } wins because (1, 0, 0) beats (0, 1, 0) and (0, 0, 1).