|$ curl https://forge-ai.dev/api/markdown?path=docs/css/cascade-layers
$cat docs/cascade-layers-(@layer).md
updated Recently·20 min read·published

Cascade Layers (@layer)

CSSAdvanced
Introduction

The @layer rule lets you explicitly control the cascade order by grouping styles into named layers. Layers have priority over specificity — styles in later layers always override earlier layers, regardless of selector specificity.

Defining Layers

Declare layers with @layer in order of priority (first declared = lowest priority).

cascade-layers.css
CSS
1/* Declare layer order (lowest to highest priority) */
2@layer reset, base, components, utilities;
3
4/* Add rules to a layer */
5@layer reset {
6 * { margin: 0; padding: 0; box-sizing: border-box; }
7}
8
9@layer base {
10 body { font-family: system-ui; line-height: 1.6; }
11}
12
13@layer components {
14 .card { padding: 1rem; border-radius: 8px; }
15}
16
17/* This overrides .card in components layer */
18@layer utilities {
19 .p-2 { padding: 0.5rem; }
20}
Layer Priority

The layer ordering takes precedence over specificity. A simple class in a higher-priority layer beats an ID selector in a lower-priority layer.

layer-priority.css
CSS
1@layer low, high;
2
3@layer low {
4 #specific { color: red; } /* Specificity 1-0-0 */
5}
6
7@layer high {
8 .simple { color: blue; } /* Specificity 0-1-0 — WINS */
9}
10
11/* Unlayered styles beat all layers */
12body { color: black; } /* Highest priority */

info

Unlayered styles have the highest priority — they beat all layers. Use layers for third-party code and reset, then keep your app styles unlayered for maximum control.