CSS: Cascade Layers
css cascade layers
work in progress ai generated
CSS Cascade Layers (@layer) – Minimal Tutorial
Cascade Layers give you explicit control over the cascade order of your CSS, independent of specificity and source order.
1. Why Layers Exist
Without layers:
- Specificity fights (
.btnvs#header .btn) - Source order matters
- Third-party CSS can be hard to override cleanly
With layers:
- You define named layers that have a fixed order
- A rule in a later layer wins, even if it has lower specificity
2. Basic Syntax
/* 1. Declare layer order (optional but recommended) */
@layer reset, base, components, utilities, theme;
/* 2. Assign rules to layers */
@layer reset {
* { margin: 0; padding: 0; box-sizing: border-box; }
}
@layer base {
body { font-family: system-ui; }
a { color: blue; }
}
@layer components {
.button {
padding: 0.5rem 1rem;
background: royalblue;
color: white;
}
}
@layer utilities {
.text-center { text-align: center; }
}
3. Key Rules
- Layer order = the order you declare in
@layerat the top (or the order they first appear) - Later layers always override earlier layers, regardless of specificity
- Rules not in any layer belong to an implicit final layer (strongest)
@layer low, high;
/* This wins even though specificity is lower */
@layer high {
.button { background: hotpink; } /* wins */
}
@layer low {
#header .button { background: navy; } /* loses */
}
4. Anonymous Layers
You can create unnamed layers (useful for third-party code):
@import "third-party.css" layer(thirdparty);
/* or */
@layer {
/* rules here go into an anonymous layer */
}
5. Nesting Layers (CSS Nesting + Layers)
@layer components {
.card {
padding: 1rem;
@layer interactive {
&:hover { transform: scale(1.02); }
}
}
}
6. Practical Pattern (Recommended)
/* 1. Layer order */
@layer reset, base, components, utilities, override;
/* 2. Reset / Normalize */
@layer reset { ... }
/* 3. Base styles */
@layer base { ... }
/* 4. Component library */
@layer components { ... }
/* 5. Your utilities (Tailwind style) */
@layer utilities { ... }
/* 6. Your final overrides */
@layer override {
.button { background: var(--brand-color); }
}
7. Quick Tips
- Use specific layer names for maintainability
- Put frameworks/libraries in early layers
- Put your custom styles in later layers
!importantstill beats everything (avoid if possible)- DevTools in Chrome/Firefox show layer names in the Styles pane
CSS, misc, advanced
- CSS: Case Sensitivity
- CSS: Declare Charset
- CSS: Comment Syntax
- CSS: Default Unit
- CSS: Computed Style
- CSS: Pseudo Element
- CSS: Pseudo Class
- CSS: Specificity
- CSS: Data URI Scheme
- HTML: Protocol-Relative URL
- CSS: Browser Default Style Sheet (2025-12)