Sub topic 7
Cascade layers: controlling precedence with @layer
This chapter assumes you can compute selector specificity, know the difference between author and user-agent origins, and understand how !important changes precedence. If any of those is unclear, review the earlier chapters on specificity and origins first.
The problem layers solve
Specificity is a blunt tool for managing precedence. Suppose a reset or third-party stylesheet uses #nav a { color: navy; }. To override it from your own code, you must either write a selector at least as specific or add !important. Both options escalate. Each override makes the next override harder, and the stylesheet becomes a specificity arms race.
Cascade layers separate two questions that specificity mixes together: which group of rules is more important and which selector inside that group is more specific. You decide the first question explicitly with @layer. Specificity only breaks ties within a single layer.
Where layers sit in the cascade
The browser compares competing declarations using these criteria, in order. The first criterion that produces a winner decides the result.
- Origin and importance
- Context (for example, shadow DOM)
- Element-attached styles (the
styleattribute) - Cascade layers
- Specificity
- Order of appearance
Layers are checked after origin and importance, and before specificity. That position explains most of their behavior. A layer can never beat an !important declaration from a higher-priority origin. But a layer with lower specificity can beat a layer with higher specificity, because the layer comparison happens first.
Declaring and ordering layers
Layer order is the order in which the layers are first named. The most compact way to name them is a statement at the top of the stylesheet:
@layer base, components;
@layer base {
#nav a { color: navy; }
}
@layer components {
a { color: teal; }
}The first line establishes that base comes first and components comes second. For normal (non-!important) declarations, later layers win over earlier layers. Here, links inside #nav are teal. The selector #nav a has specificity (1,0,1) and a has only (0,0,1), but specificity is never consulted because the layers differ.
Declaring the order up front matters because it makes the order independent of where the rule blocks appear. If you skip the statement, the order is the order in which the browser first meets each layer name, which can change when you reorder files or add imports.
Ways to create a layer
| Syntax | Effect |
|---|---|
| `@layer base, components;` | Declares layers in order, with no rules. |
| `@layer base { ... }` | Creates the layer if needed and adds rules to it. |
| `@import url("lib.css") layer(vendor);` | Places an imported stylesheet into a named layer. |
| `@layer { ... }` | Creates an anonymous layer that cannot be added to later. |
You can reopen a named layer as many times as you like. Rules from every block with the same name end up in the same layer, in source order. Reopening does not change the layer's position, which was fixed by its first appearance.
@layer reset, base, components, utilities;
@layer base {
a { color: navy; }
}
@layer components {
.card a { color: teal; }
}
@layer base {
/* Still in the base layer, so components still wins. */
a { text-decoration: underline; }
}Note that @import ... layer() must come before any rules other than @charset and @layer statements, so put your ordering statement first and your imports after it.
Unlayered styles win over layers
Any declaration that is not inside a layer behaves as if it belonged to an implicit final layer. For normal declarations, unlayered styles beat all layered styles, regardless of specificity.
@layer components {
.btn.primary.large { background: steelblue; }
}
button { background: gray; }The button rule is unlayered, so a <button class="btn primary large"> is gray, even though its competitor has specificity (0,3,0).
This gives a practical architecture. Put third-party CSS, resets and framework defaults in layers. Keep your own site-specific rules unlayered, or in the last layer. Your rules then override the library without any specificity tricks.
The cost is that wrapping existing CSS in a layer can change how it interacts with unlayered rules elsewhere on the page. Layering a stylesheet that used to win by specificity can make it lose to a simple unlayered selector.
Importance reverses the order
For declarations marked !important, layer order inverts. Earlier layers win over later layers, and unlayered !important declarations lose to layered !important ones.
@layer base, components;
@layer base {
p { color: red !important; }
}
@layer components {
p { color: blue !important; }
}
p { color: green !important; }A paragraph here is red. Among important declarations, base beats components, and both beat the unlayered rule. For normal declarations in the same stylesheet, the order would be the opposite.
The reason for the reversal is that it mirrors the origin rule you already know. For origins, important user-agent styles beat important user styles, which beat important author styles. Layers follow the same idea: the earliest layer is treated like the most foundational source, so its !important rules act as guardrails that later code cannot override. A reset layer can enforce [hidden] { display: none !important; } and no later layer can undo it.
The full order for the author origin, from lowest to highest priority:
- Normal declarations in earlier layers
- Normal declarations in later layers
- Normal unlayered declarations
- Important unlayered declarations
- Important declarations in later layers
- Important declarations in earlier layers
Each of these still sits below important user and user-agent declarations, and above normal declarations from lower origins in the usual way.
Specificity inside a layer
Within one layer, nothing changes. Specificity decides first and source order breaks ties. Layers do not reset or discount specificity. They only make it irrelevant between different layers.
@layer components {
.card a { color: navy; } /* (0,1,1) */
a { color: teal; } /* (0,0,1), loses within the layer */
}Links in .card are navy because both rules are in the same layer and the first has higher specificity.
Nested layers
A layer can contain sublayers. You create one by nesting @layer or by using dot notation in the name.
@layer framework {
@layer defaults, theme;
@layer defaults {
a { color: gray; }
}
@layer theme {
a { color: teal; }
}
}
@layer framework.theme {
a { text-decoration: none; }
}Sublayers are ordered inside their parent. The parent is compared with its siblings as a whole, so every rule in framework and its sublayers sits at the position of framework. A sublayer cannot escape its parent's rank. Unlayered rules inside framework (outside any sublayer) form an implicit last sublayer of framework and beat its named sublayers.
Layers and the style attribute
Inline styles written in a style attribute are checked before layers in the criteria list. A normal inline declaration therefore beats every layered and unlayered normal author declaration. An !important declaration in a stylesheet still beats a normal inline declaration, which is the usual rule, and an !important inline declaration beats important rules in stylesheets.
Common mistakes and edge cases
- Expecting specificity to work across layers. A
#idselector in an early layer loses to a bare element selector in a later layer. If a style seems to ignore a high-specificity selector, check layers first. - Forgetting the unlayered rule. A stray unlayered rule beats every layer. When a layered rule never applies, search for an unlayered one that targets the same property.
- Assuming the order of blocks sets the order of layers. Only the first mention of each name counts. Declare the order in a single statement at the top.
- Expecting
!importantto follow layer order. Importance reverses it, so the earliest layer wins for important declarations. - Importing after rules. A late
@importis ignored, so its layer is never created where you expect. - Overusing anonymous layers. An
@layer { }block with no name cannot be extended or referenced later, which makes debugging harder. - Using
@layerfor everything. Layers help when you manage several sources of CSS. In a single small stylesheet they add indirection without benefit.
Layers are supported in all current major browsers. Older browsers ignore @layer blocks entirely, so any rules inside are dropped. If you must support them, do not place essential styles only inside layers.
Why layers do not replace specificity knowledge
Layers shrink the number of places where specificity matters, but they do not remove it. Inside each layer you still need to compute specificity and understand source order. Developer tools show the layer name next to each rule, which is how you confirm which layer a winning declaration came from. The debugging chapter covers that in detail.
Exercise
Given the CSS below, what color is <p id="intro" class="note">Hello</p>, and why?
@layer base, theme;
@layer base {
#intro { color: green; }
}
@layer theme {
p { color: purple; }
}
Show answer
Purple. Both are normal declarations from the author origin, so the cascade compares layers before specificity. The theme layer is declared after base, so it wins for normal declarations, even though the selector p has specificity (0,0,1) and #intro has (1,0,0).
Exercise
Using the same two layers, you change both declarations to use !important. What color is the paragraph now, and what does this show about layer order?
Show answer
Green. For !important declarations the layer order is reversed, so the earlier layer (base) wins over the later layer (theme). This lets an early layer, such as a reset, set protections that later layers cannot override.
Exercise
A library is imported with @import url("lib.css") layer(vendor); and contains .btn.btn-primary { background: blue; }. Your own stylesheet, with no layers, contains button { background: gray; }. Which background does a button with those classes get, and how would you make the library rule win?
Show answer
Gray. The unlayered rule beats any layered normal declaration, regardless of specificity. To make the library win, put your rule inside a layer declared before vendor, for example @layer base, vendor; with the button rule inside base. Alternatively, remove the unlayered rule or change the library import so it is unlayered and let specificity decide.