Sub topic 14
Cascade layers with @layer
This chapter assumes you can already calculate a selector's specificity as an (IDs, classes, types) triple. It also assumes you know the cascade order of origin, specificity, and source order, and how !important works. Cascade layers add a step to that order: layer position is checked before specificity.
The problem layers solve
Specificity is a poor tool for organizing large stylesheets. Suppose a reset file contains #nav a { color: black; }. Your component file then needs a plain a { color: blue; } to win. With specificity alone you must either raise your selector to match the reset's ID or edit the reset.
Cascade layers let you declare which group of rules should win, whatever the selectors inside them look like. A layer is a named bucket of rules. Buckets are ranked, and the ranking is compared before specificity.
Declaring layers
The @layer at-rule has two forms. A block form puts rules in a layer, and a statement form only names layers and fixes their order.
@layer reset, components;
@layer reset {
#nav a { color: black; }
}
@layer components {
a { color: blue; }
}The first line is the statement form. It creates two layers and ranks them: reset first (lowest priority), components last (highest priority). The two blocks then add rules to those layers.
In this example, links inside #nav are blue. The selector #nav a has specificity (1,0,1) and a has (0,0,1). Both rules are normal declarations, and components is later than reset, so the layer decides before specificity is consulted.
Where layers sit in the cascade
For normal (non-!important) author declarations, the browser compares in this order:
- Layer order. A later layer beats an earlier one.
- Specificity, among rules in the same layer.
- Source order, among rules with equal specificity in the same layer.
Specificity is never compared across layers. A rule in an early layer cannot win by having a stronger selector.
Layer order is fixed by first mention
The position of a layer is set where its name first appears in the stylesheet, whether in a statement or a block. Reopening a layer later appends rules to it but does not move it.
@layer base { p { color: black; } }
@layer theme { p { color: green; } }
@layer base { p { color: red; } }base appeared first, so theme still ranks higher. The paragraph is green, even though the red rule is last in the file.
Because of this, the statement form is best placed on the first line of your main stylesheet. It states the whole order in one place and makes the later blocks independent of file order.
Unlayered styles beat layered styles
Rules that are not in any layer behave as if they sit in an implicit final layer. For normal declarations, they beat every named layer.
@layer components {
.btn { background: teal; }
}
button { background: gray; } /* unlayered, wins despite lower specificity */A button with class btn is gray here. The type selector button has specificity (0,0,1) and .btn has (0,1,0), but the unlayered rule wins before specificity is considered. Inline style attributes are also unlayered, so they beat layered rules too.
This behavior is useful. You can put third-party CSS and your own base styles into layers, then write unlayered overrides in a small file at the end, knowing they win.
It is also the most common mistake. If you layer your own CSS but a library's CSS is unlayered, the library wins. Put the library in a layer too, ranked below yours.
Layering imported files
@import accepts a layer() function, which places an entire file into a layer. Imports must come before other rules, except @layer statements.
@layer vendor, base, components;
@import url("normalize.css") layer(vendor);
@import url("site-base.css") layer(base);This is the cleanest way to demote a third-party stylesheet you cannot edit. Whatever selectors it uses, vendor ranks below base and components.
How !important changes the order
For !important declarations, layer order reverses. The earliest layer wins, and unlayered important rules are the weakest among author important declarations.
| Declaration type | Highest priority | Lowest priority |
|---|---|---|
| Normal | Unlayered | First declared layer |
| `!important` | First declared layer | Unlayered |
The reversal makes sense when you consider the purpose. A reset or vendor layer that marks something !important is saying that this value must hold. Later layers and unlayered code cannot override it.
@layer base, theme;
@layer base { p { color: red !important; } }
@layer theme { p { color: blue !important; } }
p { color: green !important; }The paragraph is red. Among important declarations, base ranks highest, then theme, then unlayered.
The comparison between origins still comes first. User-agent !important rules beat author !important rules, and author important rules beat normal ones. Layers only reorder declarations inside the author origin.
Nested and anonymous layers
Layers can be nested by writing a dotted name or by placing a block inside another block.
@layer framework {
@layer base, widgets;
@layer widgets { .card { padding: 1rem; } }
}
@layer framework.base {
.card { padding: 0; }
}The nested layer framework.widgets ranks above framework.base, because base was named first inside framework. Nested layers are ordered within their parent, and the parent is ordered among its siblings. A rule in an unnested part of framework beats the rules in framework's nested layers, with the same "unlayered wins" logic applied one level down.
A block with no name, @layer { ... }, creates an anonymous layer. It takes a position where it appears, but you cannot add rules to it later. Anonymous layers are rarely useful in hand-written CSS.
Layers do not touch inheritance
Layers only affect competition between declarations that target the same element and property. Inheritance works as before: a value passed down from a parent is still lower priority than any rule that matches the child directly. A rule in the weakest layer, reset, that matches the child still beats an inherited value from a parent in the strongest layer.
Reverting to an earlier layer
The revert-layer keyword rolls a property back to the value it would have had if the current layer had not set it. This works well for variants.
@layer base, overrides;
@layer base {
a { color: navy; }
}
@layer overrides {
a { color: crimson; }
a.plain { color: revert-layer; }
}A link with class plain is navy. The a.plain rule discards the overrides layer's value, so the cascade falls back to base.
Common errors
- Layering your code but not the library. Unlayered rules win, so the library overrides you. Wrap it with
@import ... layer(name). - Declaring layers after using them. If
componentsappears before the statement@layer reset, components;appears, the order is set by the earlier use. Put the order statement first. - Expecting specificity to rescue a low layer. Raising a selector's specificity does nothing across layers. Move the rule to the right layer instead.
- Using
!importantand expecting the usual order. In layers it is reversed, as the table shows. - Mixing
@importplacement. An@importplaced after normal rules is ignored.
Layers and low-specificity strategy
Layers combine well with :where(). Inside a layer, :where() keeps specificity at zero. Between layers, the order decides. Together, they let you write a stylesheet where almost nothing needs !important or an ID to win.
Exercise
Given @layer a, b; with @layer a { #x { color: red; } } and @layer b { p { color: blue; } }, what color is <p id="x">? What color is it if both declarations are marked !important?
Show answer
Blue for normal declarations, because layer b ranks higher than a and specificity is not compared across layers. With !important on both, it is red, because important declarations reverse the layer order and the earliest layer, a, wins.
Exercise
A third-party stylesheet is unlayered, and your own rules are in @layer components. The library's .btn { color: gray; } and your .btn { color: teal; } both match. Which wins, and how do you fix it without editing your own rules?
Show answer
The library's gray wins, because unlayered normal declarations beat layered ones. Import the library with @import url("lib.css") layer(vendor); and declare vendor before components, for example @layer vendor, components;. Then your teal wins.