Sub topic 1
Where Cascade Layers Fit in the Cascade
Prerequisites
You should know CSS selectors, declarations, specificity, source order, and how to inspect styles in browser DevTools. This chapter assumes that a cascade conflict means two or more declarations set the same property on the same element.
Where Cascade Layers Fit in the Cascade
The CSS cascade decides which declaration wins. In simplified form, it considers:
- Origin and importance, such as author CSS and
!important. - Cascade layer order.
- Selector specificity.
- Source order.
A cascade layer is a named group of rules. For normal declarations, a later layer wins over an earlier layer before specificity is considered. This means a low-specificity rule in a later layer can beat a high-specificity rule in an earlier layer.
Declaring Layers with `@layer` Blocks
Use a block form when you want to place rules inside a layer:
@layer base {
#nav a.link {
color: blue;
}
}
@layer utilities {
.red {
color: red;
}
}For an element matching both selectors, the .red declaration wins because utilities comes after base. The selector in base has greater specificity, but specificity is checked only after layer priority.
A layer can contain any valid CSS rules, including nested rules and media queries.
Setting Layer Order with an `@layer` Statement
Set the order explicitly with a comma-separated statement:
@layer reset, base, components, utilities;
@layer reset {
* {
box-sizing: border-box;
}
}
@layer utilities {
.text-red {
color: red;
}
}The statement creates the layer order before the blocks add their rules. utilities therefore outranks reset, base, and components, even if its block appears earlier or later in another file.
This predictable order lets a project separate concerns: resets establish defaults, base styles define elements, components style reusable parts, and utilities provide intentional final adjustments.
Exercise
A base rule uses #app p { color: blue; }. A later utilities layer uses .text-red { color: red; }. Which color applies when both match?
Show answer
Red. The later utilities layer wins before specificity is compared.