Sub topic 7
Controlling order with @layer
Prerequisites
This chapter assumes you know the following:
- How specificity and source order decide which rule wins.
- How to link stylesheets and use
@import. - The BEM and layered-architecture ideas from the earlier chapters.
You do not need a build tool, but the examples are easier to try in a bundler-free page with two or three <link> elements.
The problem layers solve
Without layers, the cascade decides conflicts in this order: importance, then specificity, then source order. Specificity is the weak point in large codebases. A utility such as .p-0 has one class of specificity, so any component selector with two classes beats it. Teams then reach for !important, ID selectors, or longer selectors, and the stylesheet gets harder to change.
The @layer at-rule adds a step before specificity. You group rules into named layers and declare the order of those layers once. When two normal declarations conflict, the one in the later layer wins, whatever its specificity.
How layers fit into the cascade
Layers sit between importance and specificity. The browser compares declarations in this order:
- Origin and importance (user agent, user, author, and
!important). - Layer order.
- Specificity.
- Source order.
Specificity and source order still work, but only among rules in the same layer. Layers also don't change a selector's specificity. A layer only changes which declaration is compared first.
Declaring the order once
Put one @layer statement at the top of your entry stylesheet. It lists the layer names and sets their order without containing any rules.
@layer reset, base, components, utilities;The first time the browser sees a layer name, it fixes that layer's position. Later @layer blocks with the same name add rules to the existing layer and do not move it. Because of this, a single statement before everything else makes the order independent of how files load.
Here is a full example. The component selector is far more specific than the utility, yet the utility wins.
@layer reset, base, components, utilities;
@layer reset {
* { box-sizing: border-box; margin: 0; }
}
@layer components {
#sidebar .card.card--featured {
padding: 2rem;
}
}
@layer utilities {
.p-0 { padding: 0; }
}For <article id="sidebar"><div class="card card--featured p-0">, the computed padding is 0. The utilities layer is later, so specificity is never compared.
Putting rules into layers
You can assign rules to a layer in three ways.
- A block:
@layer components { ... }. - An import:
@import url("components.css") layer(components);. - A nested name, covered below.
You can also write an anonymous layer, @layer { ... }. Nothing can refer to it again, so it is rarely useful. The order of anonymous layers follows the order in which they appear.
Layering third-party CSS
Imports are the cleanest way to contain vendor CSS. Put the vendor code in a low layer and your code wins without any override tricks.
@layer reset, vendor, base, components, utilities;
@import url("normalize.css") layer(reset);
@import url("datepicker.css") layer(vendor);@import rules must come before all other rules, except @charset and @layer statements. That is why the order statement can sit above the imports. Imports are also a performance cost, since each one is a separate request that the browser finds late. In a production build, a bundler can inline them, and the layer assignment is preserved.
Nested layers
A layer can contain layers. This lets a component library keep its own internal order without adding to the top-level list.
@layer components {
@layer base, variants;
@layer base {
.button { padding: 0.5rem 1rem; background: #eee; }
}
@layer variants {
.button--primary { background: #0b5fff; color: #fff; }
}
}You can write the same structure with dot notation, for example @layer components.variants { ... }. Nested layers are ordered inside their parent. All of components still sits in one position relative to utilities.
Unlayered styles win
Any rule that is not in a layer is treated as if it were in a final, implicit layer that comes after all named layers. For normal declarations, unlayered rules beat every layered rule.
@layer components {
.card { padding: 1rem; }
}
.card { padding: 2rem; } /* unlayered, so this wins */This is the most common surprise when you adopt layers. If you wrap your new code in layers but leave legacy CSS unlayered, the legacy code wins, even if it comes earlier in the file.
The table below summarises which declaration wins for normal (non-!important) rules.
| Situation | Winner |
|---|---|
| Same layer | Higher specificity, then later source order |
| Different named layers | The later layer, regardless of specificity |
| Layered against unlayered | The unlayered rule |
| Inline `style` attribute against layers | The inline style, because it is unlayered |
!important reverses the order
For !important declarations, the layer order is flipped. The earliest layer wins, and layered !important rules beat unlayered !important rules.
@layer base, utilities;
@layer base {
.box { color: red !important; }
}
@layer utilities {
.text-blue { color: blue !important; }
}An element with both classes is red. The reversal is deliberate. It lets a low layer such as reset or a vendor layer protect a critical rule from later overrides.
Choosing a layer order
A good order follows the idea from the layered-architecture chapter: low specificity and broad reach first, narrow and strong rules last.
reset: box-sizing, margin resets, normalisation.vendor: third-party CSS you want to override.base: element defaults such asbody,a, headings and form controls.components: BEM blocks and their modifiers.utilities: single-purpose helpers that must win.
Keep the list short. Each layer is a rule you must explain to the rest of the team, and every extra layer is another place for a rule to be in the wrong one.
Common errors
- The order statement comes too late. If a stylesheet loaded earlier mentions
componentsfirst, that file sets the position. Keep the statement in the first file loaded, or at the top of the entry file. - Mixing layered and unlayered code. Unlayered code beats all layers. Move legacy CSS into a layer named
legacy, placed where you want it in the order, and shrink it over time. - Expecting layers to lower specificity. Inside a layer, specificity works as usual. A selector that is too specific in
componentsstill beats a simple one in the same layer. - Misspelled layer names.
@layer componentand@layer componentsare different layers. The typo creates a new layer at the end of the order. It then beats everything declared before it. - Assuming old browsers degrade gracefully. A browser that does not support
@layerignores the whole block, so its rules are dropped. Layers are supported in all current major browsers. Check your support targets before relying on them, or provide a fallback stylesheet. - Placing
@importafter other rules. The import is ignored.
Migrating an existing codebase
You can adopt layers without rewriting everything.
- Add the order statement with a
legacylayer placed where the current behaviour is closest. If legacy rules should beat new components, putlegacyafter them. - Import the old stylesheets with
layer(legacy), so they are no longer unlayered. - Write new components inside
components. - Remove
!importantand ID selectors from the legacy layer as you touch them. The order of layers can now do the job. - Add a Stylelint rule or code review check so new rules are never written unlayered.
Exercise
Given this CSS, what is the padding of <div class="card p-0">, and why?
@layer components, utilities;
@layer utilities { .p-0 { padding: 0; } }
@layer components { .card.card--wide, .card { padding: 2rem; } }
Show answer
The padding is 0. The statement on the first line fixes the order as components, then utilities. Declaring the utilities block first in the file does not change that. The later layer wins for normal declarations, so .p-0 beats .card despite its lower specificity.
Exercise
A page has @layer base, components; at the top. A teammate adds a { color: green; } outside any layer, and .link { color: blue; } inside components. Which colour does <a class="link"> get, and what is the simplest fix if you want blue?
Show answer
It is green, because unlayered rules beat all layered rules. The simplest fix is to move the a rule into the base layer. Then components wins and the link is blue.
Exercise
Both .box { color: red !important; } in the base layer and .text-blue { color: blue !important; } in the later utilities layer apply to one element. Which colour wins, and why is this different from the normal case?
Show answer
Red wins. For !important declarations the layer order is reversed, so the earliest layer wins. This lets a low layer protect a rule from overrides in later layers.