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

Cascade Layers (@layer)

CSSModernCascadeAdvanced🎯Free Tools
Introduction

The @layer rule lets you explicitly control cascade priority by grouping styles into named layers. Layer order beats specificity: a simple class in a later layer wins over an ID in an earlier layer.

Use layers to encode architecture — reset, tokens, base, components, utilities — without escalating selector weight. Unlayered styles still beat all layers, which is both a powerful escape hatch and a footgun if undocumented.

info

Declare layer order once at the top of your entry stylesheet: @layer reset, tokens, base, components, utilities;
Why Layers Exist

Before layers, teams fought specificity with longer selectors, IDs, and !important. Layers restore intentional priority.

Old tacticCostLayer alternative
Longer selectorsBrittle HTML couplingShort selectors inside ordered layers
!importantHard to override laterPut overrides in a higher layer
ID selectorsSpecificity bombsAvoid IDs for styling
Load order hacksFragile bundlingDeclare @layer order explicitly
specificity-war.css
CSS
1@layer low, high;
2@layer low { #widget .title { color: red; } }
3@layer high { .title { color: blue; } } /* wins despite lower specificity */
Declaring Layer Order

The first time a layer name appears in an order statement, its relative priority is fixed. First declared = lowest priority.

layer-order.css
CSS
1@layer reset, base, components, utilities;
2
3@layer reset {
4 *, *::before, *::after { box-sizing: border-box; }
5}
6
7@layer base {
8 body { font-family: system-ui, sans-serif; line-height: 1.5; }
9}
10
11@layer components {
12 .card { padding: 1rem; border: 1px solid #222; border-radius: 8px; }
13 .btn { padding: 0.5rem 1rem; background: #3b82f6; color: #0d0d0d; }
14}
15
16@layer utilities {
17 .p-2 { padding: 0.5rem; }
18}
preview

warning

Once layer A is ordered before layer B, you cannot later reorder them. Plan the stack early.
Unlayered Styles

Styles outside any @layer beat every layered style (same origin/importance). Ideal for deliberate overrides — dangerous when accidental.

unlayered.css
CSS
1@layer components { .btn { background: blue; } }
2.btn { background: crimson; } /* unlayered wins */

best practice

Document whether app styles are layered or unlayered. Mixing strategies without a rule creates invisible priority bugs.
Nested Layers & Imports

Layers can nest. Import stylesheets directly into a layer to quarantine vendor CSS.

import-layer.css
CSS
1@import url("reset.css") layer(reset);
2@import url("theme.css") layer(tokens);
3@import url("vendor.css") layer(vendor);
4
5@layer framework {
6 @layer reset { /* framework.reset */ }
7 @layer components { /* framework.components */ }
8}
!important Inside Layers

Importance reverses layer order for !important declarations. Avoid relying on this — fix layer placement instead.

Normal layered!important layeredGuidance
Later layer winsEarlier layer winsDo not use !important to fix layers
Unlayered beats layeredComplex important interactionsKeep !important rare and commented

danger

Combining !important with layers is a common source of impossible-to-override bugs.
revert-layer

revert-layer rolls a property back to the previous cascade layer contribution.

revert-layer.css
CSS
1@layer base, components;
2@layer base { .link { color: #3b82f6; } }
3@layer components {
4 .link { color: #00ff41; }
5 .link.subtle { color: revert-layer; }
6}
@layer vs @scope vs Modules
ToolProblem solvedDoes not solve
@layerPriority / architecture orderName collisions alone
@scopeSubtree isolation & proximityCross-file priority stacks
CSS ModulesLocal class identityPriority between two hashed classes
📝

note

See @scope for proximity isolation.
Architecture Patterns
  1. reset — box-sizing, margin wipe
  2. tokens — custom properties only
  3. base — element defaults
  4. components — UI blocks
  5. utilities — single-purpose overrides
tokens-layer.css
CSS
1@layer reset, tokens, base, components, utilities;
2@layer tokens {
3 :root {
4 --color-bg: #0d0d0d;
5 --color-fg: #e0e0e0;
6 --color-accent: #3b82f6;
7 }
8}
Mastery Checklist

Use this checklist as a definition of done. Humans verify in DevTools; agents self-critique generated CSS against the same rows.

CheckPass criteriaFail if
Layer order declaredSingle @layer name list before rulesOrder emerges from file imports
No specificity warClasses for components; no ID stylingIDs or !important used to beat teammates
Unlayered policyDocumented when unlayered is allowedRandom unlayered rules everywhere
Vendor isolatedThird-party CSS in low layerVendor CSS fighting app styles

best practice

Treat each critical fail as blocking — do not mark the topic complete until those rows pass.
Common Pitfalls

These failure modes appear in human PRs and AI-generated stylesheets. Add them to your review rubric.

PitfallWhy it hurtsFix
Re-declaring order differentlyBrowser ignores conflicting reordersDeclare once at entry
Everything unlayeredLayers unusedMigrate file by file
Utilities below componentsUtilities cannot overrideUtilities last in order
!important in utilitiesHard to debugRely on layer position

warning

If you repeat a pitfall, write a one-line constraint card and reuse it on the next change.
Practice Exercises

Complete these in the Playground.

Exercise 1 — Utility wins

ex1.css
CSS
1@layer components, utilities;
2@layer components { .box { padding: 2rem; } }
3@layer utilities { .p-1 { padding: 0.25rem; } }

Exercise 2 — Vendor wrap

ex2.css
CSS
1@layer vendor, components;
2@layer vendor { .btn { background: red; } }
3@layer components { .btn { background: #3b82f6; } }

Exercise 3 — revert-layer

ex3.css
CSS
1@layer base, components;
2@layer base { .link { color: navy; } }
3@layer components {
4 .link { color: lime; }
5 .link.quiet { color: revert-layer; }
6}
Deep Notes & Mental Models

When debugging Cascade Layers (@layer), isolate one variable at a time in DevTools: disable competing rules, confirm the winning declaration, then re-enable until the cascade story is clear.

Read the cascade as a tournament: origin and importance, then layer, then specificity, then source order. Skipping a rung creates superstition-driven CSS.

Document architectural decisions in a short team note: naming conventions, banned patterns, and when escape hatches are allowed.

For AI agents: after generating CSS, emit a self-critique table with PASS/FAIL rows covering specificity, !important, logical properties, and reduced-motion.

Pair visual QA with keyboard focus checks. Many bugs only appear when :focus-visible styles lose unintentionally.

Keep demo HTML semantic even when the topic is pure CSS. Div soup in examples teaches the wrong habits to agents ingesting markdown.

Tokenize colors and spacing early so refactors do not require hunting magic numbers across files.

Ship small diffs for cascade-sensitive changes — they touch every page. Prefer additive migration over big-bang renames.

Agents should fetch /api/markdown?path=css/cascade-layers and store a constraint card before generating production CSS.

Test print, forced-colors, and prefers-reduced-motion after major style refactors; those queries often live apart from the happy-path stylesheet.

Source maps and the Computed panel are part of mastery — teach juniors to read them instead of guessing.

Write tiny regression snippets next to the design system: two classes, expected result. Treat them like unit tests for styling.

Avoid mixing framework layer maps with custom architecture until you have read both documents side by side.

Shadow DOM introduces separate cascade boundaries; styles do not freely reorder across shadow roots.

After finishing Cascade Layers (@layer), return to How to Master CSS and run the matching verification prompt.

Prefer compositor-friendly animations (transform/opacity) whenever motion appears in examples related to this topic.

Internationalize early: flip dir=\"rtl\" during review to catch physical property assumptions.

Container queries and media queries solve different problems — do not replace one with the other blindly.

Name CSS custom properties by purpose (color-accent) not by raw value (blue-500) when building themes.

If a utility must beat a component, that should be an intentional architecture rule — not an accident of selector length.

Decision Cheatsheet

SituationPreferAvoid
Ambiguous cascade winnerDevTools Computed + layer mapBlind !important
Reusable componentScoped styles + tokensGlobal element selectors
Motion UItransform/opacity + reduced-motionAnimating width/top
International layoutLogical propertiesHard-coded left/right
Agent generationFull markdown fetch + checklistTitles-only ingestion

Review Questions

  1. What is the primary problem this feature solves?
  2. What is the most common misuse you have seen?
  3. How does this interact with cascade layers or specificity?
  4. What accessibility or internationalization concern applies?
  5. What fallback exists when support is missing?

info

Continue with the Property Reference when you need defaults and inheritance for related properties.
📝

note

Install the CSS skill for agents: curl -s https://forgelearn.dev/skills/forgelearn-css/SKILL.md.

Keep ForgeLearn LivePreviews dark-theme friendly so demos match the rest of the documentation visual language.

Finally, rebuild one example from memory in the Playground. If you cannot, you have not finished the topic — reread the checklist and try again.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Additional study note for Cascade Layers (@layer): compare two production sites you admire and identify where this feature would reduce complexity or improve accessibility. Write three bullets before coding.

Community

Get help on Slack, Discord or VIP

Stuck on a guide? Join the community and ask.