Custom Properties and Modern CSS Features
CSS variables, container queries, :has(), nesting, cascade layers and other features that replaced many preprocessor and JavaScript tricks.
Intermediate · about 5 hours · difficulty 3/5
Learn first: Responsive Design
CSS has changed more in the last few years than in the decade before. Many things that used to need Sass or JavaScript are now native.
Custom properties (CSS variables)
--brand: oklch(60% 0.2 250); defined on :root and used as color: var(--brand). Unlike Sass variables they are live: they cascade, inherit, can change inside media queries or on a class, and JavaScript can update them. This is the foundation of theming and dark mode (swap a handful of tokens, not every rule). Provide fallbacks with var(--x, 1rem).
Container queries
container-type: inline-size on a wrapper, then @container (min-width: 400px) { ... } styles a component based on its own available space rather than the viewport. A card can be compact in a sidebar and wide in the main column with the same CSS.
Relational and structural selectors
:has()is the long-awaited parent selector:.card:has(img), orform:has(:invalid)to style a form that contains errors.- Native nesting (
.card { & h2 { ... } }) now works in all modern browsers. @layerorganises resets, base, components and utilities so specificity fights disappear.
Also worth knowing
Logical properties (margin-inline, padding-block) for right-to-left support, aspect-ratio, accent-color, color-mix(), the oklch() colour space, @supports for feature detection, and scroll-driven animations and view transitions for newer projects.
Pitfall
Check support on caniuse or MDN's compatibility tables before depending on the very newest features, and design so the page still works if a feature is missing.
Move on when you can build a themeable component with custom properties that also adapts with a container query.
Key concepts
- Custom properties and theming
- Container queries
- :has() relational selector
- Native CSS nesting
- Cascade layers
- Logical properties
- aspect-ratio, color-mix() and oklch()
- @supports and progressive enhancement
- View transitions and scroll-driven animations
Mini project
Build a product card that switches between stacked and horizontal layouts via a container query, supports light, dark and a brand theme through custom properties, and highlights itself with :has() when its checkbox is selected.
Check yourself
How is a CSS custom property fundamentally different from a Sass variable?