Sub topic 1
Rules, Selectors and Declarations: The Inputs to the Cascade
The cascade is an algorithm. It needs input, and that input is the set of CSS declarations that apply to each element. This chapter covers how those declarations are written and parsed, and how the browser decides which ones apply to which elements. The later chapters on origins, specificity, source order and layers cover how the algorithm picks a winner. Here you learn what it picks from.
Prerequisites
This chapter assumes you can do the following:
- Read basic HTML structure: elements, attributes,
classandid, and nesting. - Write simple CSS rules with a selector and a few declarations.
- Open your browser's developer tools and inspect an element.
You don't need to know anything about specificity or inheritance yet.
Anatomy of a rule
A CSS rule (also called a rule set) has two parts: a selector and a declaration block.
.note {
color: blue;
font-size: 1.125rem;
}.noteis the selector. It describes which elements the rule is about.- The braces
{ }enclose the declaration block. color: blue;is a declaration. It has a property (color), a colon, a value (blue), and a closing semicolon.
The semicolon separates one declaration from the next. The last one may omit it, but you should always write it, because adding a declaration later is a common source of silent bugs (see "Common errors" below).
A declaration can also end with !important, as in color: blue !important;. That flag changes how the declaration is ranked. It is covered in the chapter on origins and importance.
A stylesheet is a list of rules and at-rules such as @media, @layer and @import. Some at-rules contain rules of their own. Conditional at-rules like @media and @supports decide whether the rules inside them are active at all.
Selectors: choosing which elements a rule applies to
The browser matches each selector against each element in the document. If the selector matches, the rule's declarations become candidates for that element. If it doesn't, the rule is ignored for that element.
| Selector kind | Example | Matches |
|---|---|---|
| Type | `p` | Every `<p>` element |
| Class | `.note` | Elements whose `class` list contains `note` |
| Id | `#intro` | The element whose `id` is `intro` |
| Attribute | `a[href^="https"]` | Links whose `href` starts with `https` |
| Pseudo-class | `a:hover`, `li:first-child` | Elements in a particular state or position |
| Pseudo-element | `p::first-line` | A generated part of an element |
| Universal | `*` | Every element |
A compound selector joins several simple selectors with no space between them. p.note#intro means "a <p> that has class note and id intro". All parts must match.
Combinators relate elements to each other:
article p(descendant) matches any<p>inside an<article>, at any depth.article > p(child) matches only a<p>that is a direct child.h2 + p(adjacent sibling) matches a<p>immediately after an<h2>.h2 ~ p(general sibling) matches any later<p>sharing the same parent.
A complex selector is a chain of compound selectors and combinators, such as nav > ul a:hover. The browser matches complex selectors from right to left. It finds elements that match the rightmost compound (a:hover) and then checks whether the rest of the chain fits their ancestors.
Selector lists
A comma separates selectors that share one declaration block:
h1, h2, h3 {
font-family: Georgia, serif;
}This is shorthand for three separate rules. Each selector in the list matches independently, and later chapters rely on this: when you count specificity, you count each selector on its own.
A list has one failure mode. If any selector in a comma-separated list is invalid, the browser drops the whole rule.
h1, h2, h3:unknown-state {
margin-bottom: 1rem;
}Here :unknown-state is not a real pseudo-class. The browser can't parse the third selector, so none of h1, h2 or h3 receives the margin. The functional pseudo-classes :is() and :where() are more forgiving: they ignore an invalid argument and keep the valid ones. A later chapter covers them in the context of specificity.
Declarations: one property, one value
Each declaration sets one property to one value. The cascade compares declarations property by property. It never ranks one whole rule against another. A rule that loses for color can still win for margin.
Shorthands expand to longhands
Some properties are shorthands, which set several related longhand properties at once. margin: 0 auto; is shorthand for four longhands:
.card {
margin: 0 auto;
}
/* Equivalent to: */
.card {
margin-top: 0;
margin-right: auto;
margin-bottom: 0;
margin-left: auto;
}The cascade works on longhands. A shorthand declaration gets expanded first, and each resulting longhand takes part in the cascade separately. This has a practical consequence:
.card {
margin-left: 2rem;
margin: 0;
}The second declaration sets margin-left too, so margin: 0 overrides the earlier margin-left: 2rem. A shorthand also resets every longhand it covers, including the ones you didn't write. Using background: red resets background-image, background-repeat and the rest to their initial values.
Invalid declarations are dropped
When the browser can't parse a declaration, it discards that one declaration and keeps the rest of the rule. A declaration can be invalid because the property name is unknown, because the value doesn't fit the property's grammar, or because the syntax is broken.
.box {
width: 50%;
width: calc(100% - 2rem);
color: bluu;
padding: 1rem;
}Here color: bluu is thrown away because bluu isn't a color. width and padding still apply. If the browser doesn't understand calc(), it drops the second width, and the first stays as a fallback. This is the basis of the old "write the fallback first" pattern.
The browser discards invalid declarations at parse time, before the cascade runs. A discarded declaration is not a candidate, so it can't beat anything. This differs from a declaration that is valid but loses the cascade. Developer tools show the two cases differently (see the last section).
A different failure happens when a value is valid in syntax but meaningless in context. For example, display: flex is valid on every element, but gap does nothing on a plain block. The browser keeps such declarations as candidates. They just have no visible effect.
Duplicates inside one block
If the same property appears twice in one declaration block, both declarations are candidates. The later one wins, because of source order.
Where declarations come from
Candidates for an element can come from several places:
- The browser's built-in stylesheet. For example,
<h1>is bold and large before you write any CSS. - Stylesheets you write, linked with
<link>or embedded in<style>. - The
styleattribute on the element itself, for example<p style="color: red">. - Styles the user has configured, such as a minimum font size or a forced-colors mode.
A style attribute is a declaration block without a selector. It targets only its own element. The next chapter explains how the cascade ranks these sources by origin. For now, treat them all as supplying candidates.
From rules to candidate declarations
Putting these pieces together, the browser builds the candidate list in four steps:
- Parse every stylesheet into rules, dropping invalid declarations and rules with invalid selectors.
- For one element, test every selector and keep the rules that match.
- Expand shorthands into longhands.
- Group the surviving declarations by property.
A worked example
Consider this markup and stylesheet:
<p id="intro" class="note">Hello</p>p {
color: black;
margin: 0;
}
.note {
color: blue;
margin-bottom: 1rem;
}
p, .note {
font-size: 1.125rem;
}
h1 {
color: red;
}The h1 rule doesn't match the paragraph, so it contributes nothing. The three other rules match. The p, .note list matches through both selectors, and the browser treats it as one declaration source. After expansion and grouping, the paragraph has these candidates:
| Property | Candidates (in source order) |
|---|---|
| `color` | `black` from `p`, `blue` from `.note` |
| `margin-top` | `0` from `p` |
| `margin-right` | `0` from `p` |
| `margin-bottom` | `0` from `p`, `1rem` from `.note` |
| `margin-left` | `0` from `p` |
| `font-size` | `1.125rem` from `p, .note` |
Only color and margin-bottom have a conflict. The other properties have exactly one candidate, so that candidate wins without any further comparison. The remaining chapters of this tutorial explain how the cascade settles the two conflicts. Here the result is blue and 1rem. If a property has no candidate at all, the value comes from inheritance or from the property's initial value, which later chapters cover.
Common errors
These mistakes produce "my CSS does nothing" symptoms before the cascade is even involved.
- Missing semicolon. In
color: bluefollowed bymargin: 0on the next line, the browser reads the value asblue margin: 0, which is invalid. It drops that declaration and possibly the next. Always end declarations with a semicolon. - Typos in property or value.
colour: blueanddisplay: flexboxare both invalid and silently ignored. - One bad selector in a list. An unsupported or misspelled pseudo-class in a comma-separated list discards the whole rule. If a rule works with one selector and fails when you add another, suspect the new selector.
- Selector that matches nothing.
.Notedoesn't matchclass="note", because class names are case-sensitive in standards mode. A descendant combinator likeul .itemfails if the.itemisn't inside aul. - Assuming a rule applies as a whole. A rule is a bundle of independent candidate declarations. When something is overridden, find out which property lost and why.
Checking candidates in developer tools
Open the Styles panel for an element. It lists every matching rule, with the file and line. A declaration that is valid but loses the cascade appears with a line through it. A declaration that the browser couldn't parse also shows a warning icon, which means it was never a candidate. A rule whose selector doesn't match the element won't appear in the list at all. Reading these three states, struck through, flagged invalid and absent, is the first step of cascade debugging. The final chapter returns to this in detail.
Exercise
Given the stylesheet below, which declarations are candidates for the color and padding-left properties of <li class="item">? Which parts of the stylesheet are discarded at parse time?
li.item, li:not-a-real-class { color: green; }
li { padding: 0 1rem; color: gray; }
.item { padding-left: 2rem; colr: red; }
Show answer
The first rule has an invalid selector in its list (:not-a-real-class), so the whole rule is dropped and color: green is not a candidate. In the third rule, colr: red is dropped as an unknown property, but padding-left: 2rem stays. The candidates for color are only gray from li. The candidates for padding-left are 1rem (expanded from padding: 0 1rem in the li rule) and 2rem from .item. Choosing between those two is the cascade's job, covered in later chapters.
Exercise
A rule has the declarations margin-top: 3rem; followed by margin: 0; in the same block. What is the final top margin, and why?
Show answer
It is 0. The shorthand margin: 0 expands to four longhands, including margin-top: 0. Both margin-top declarations are candidates, and the later one in the block wins. The shorthand silently reset a longhand you wrote earlier.