CSS Reference ยท At-rules
The @layer at-rule
Reference for the CSS @layer at-rule: declare cascade layers, control their order, nest and import them, and see how layers beat specificity.
The @layer at-rule creates cascade layers: named groups of rules whose priority is decided by the order of the layers, not by selector specificity. A rule in a later layer beats a rule in an earlier layer even if the earlier selector is far more specific.
This makes it practical to organise a stylesheet as "reset, then base, then components, then utilities" without specificity wars. Rules that are not in any layer beat all layered rules (for normal declarations).
@layer reset, base, components; @layer components { .button { padding: 0.5rem 1rem; } }
Try it
Syntax
/* 1. statement: only declares the order */ @layer one, two, three; /* 2. block: declares (if needed) and adds rules */ @layer two { /* rules */ } /* anonymous layer */ @layer { /* rules */ } /* nested layers */ @layer framework { @layer base { } @layer theme { } } @layer framework.base { } /* import into a layer */ @import url(lib.css) layer(vendor);
- Order is set by the first time a layer name appears; later blocks with the same name add to the layer without changing its position.
- Priority: for normal declarations, later layers beat earlier layers, and unlayered styles beat all layers.
!importantreverses it: among important declarations, earlier layers win, and unlayered ones lose to layers.
Values
| Syntax and arguments | Description |
|---|---|
@layer a, b, c; |
Declare the order without any rules. |
@layer a { ... } |
Rules inside layer a. |
@layer { ... } |
Anonymous layer; it cannot be added to later. |
@layer a.b { ... } |
Sub-layer b of layer a. |
@import url(x) layer(a) |
Put an imported sheet into layer a. |
<style> / <link> |
Layers apply across all sheets on the page by name. |
Usage notes
- Declare the order first, on the first line of your main stylesheet, so imported or later sheets cannot reorder it by accident.
- Third-party CSS is easiest to override when you place it in a low layer: your unlayered rules then always win.
- Specificity still matters inside a layer, as does source order.
- Unlayered means highest (for normal rules). Mixing layered and unlayered code can surprise you; migrate everything or be deliberate.
- Inline
styleattributes beat layered and unlayered author styles alike, apart from!importantinteractions. - Animations:
@keyframesand@font-faceinside layers follow the same ordering for duplicate names. - Use
revert-layerto roll a property back to the value of a lower layer. - Nesting and cascade layers are different features;
@layercan appear inside nested style rules.
Browser support
Baseline since March 2022; supported in all current browsers.
Related
@import@scope@media- Lesson: Cascade Layers
- Lesson: Specificity
- Lesson: The Cascade