CSS Advanced
Cascade layers, design tokens, container queries, and performance-aware modern CSS.
Advanced CSS: Architecture & Modern Features
What You'll Learn
Beyond everyday layout, advanced CSS covers cascade layers, custom properties, container queries, and performance-minded techniques like content-visibility. This page ties them together for scalable stylesheets.
@layerfor predictable cascade ordering- Design tokens with
:rootandvar() - Container queries for component-level responsiveness
- Rendering hints and when to use them safely
Large projects fail when specificity wars escalate. Layers and tokens reduce coupling; container queries let you ship reusable components that adapt to their parent, not only the viewport.
Cascade Layers (@layer)
Theory: Layers define order of precedence: e.g. reset < base < components < utilities. Within a layer, normal specificity rules apply; between layers, the layer order wins.
Example: Layer stack
@layer reset, base, components, utilities;
@layer reset {
* { box-sizing: border-box; }
}
@layer base {
body { font-family: system-ui, sans-serif; line-height: 1.6; }
}
@layer components {
.btn { border-radius: 8px; padding: 0.5rem 1rem; }
}
@layer utilities {
.u-hidden { display: none !important; }
}
!important everywhere except where truly needed in the utilities layer.Custom Properties (Design Tokens)
Theory: Variables let you theme an app, support dark mode, and centralize spacing and radii. Scope variables on :root or on a component class.
Example: Tokens + dark mode
:root {
--color-bg: #ffffff;
--color-fg: #0f172a;
--radius-md: 10px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-bg: #0f172a;
--color-fg: #f8fafc;
}
}
.card {
background: var(--color-bg);
color: var(--color-fg);
border-radius: var(--radius-md);
}
Container Queries
Theory: Media queries depend on viewport width; container queries depend on the size of a containing element. Ideal for cards that appear in sidebars and main columns at different widths.
Example
.card-wrap {
container-type: inline-size;
}
.card {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
@container (min-width: 500px) {
.card {
flex-direction: row;
align-items: center;
}
}
Performance: content-visibility
Theory: For long lists offscreen, content-visibility: auto can skip rendering work. Use with care: test for accessibility (scroll anchoring, find-in-page) and always set explicit size where possible.
Example (simplified)
.feed-item {
content-visibility: auto;
contain-intrinsic-size: 0 200px;
}
Summary
Combine layers for cascade sanity, tokens for theming, and container queries for component fidelity. Measure performance, keep accessibility in mind, and validate CSS with the W3C validator as you grow your stylesheet.