Modern CSS in 2026: Container Queries, :has(), Cascade Layers, and the Features That Replace JavaScript
A practical tour of the modern CSS features you can ship today: native nesting, container queries, the :has() selector, cascade layers, @scope, view transitions, anchor positioning, popovers, and modern color. Learn what each solves, how to use it, and which JavaScript and preprocessor code it lets you delete.
Table of Contents
- Introduction
- Native CSS Nesting
- Container Queries
- Size Queries
- Container Query Units
- Style Queries
- The :has() Selector
- Cascade Layers with @layer
- Scoped Styles with @scope
- Modern Color: oklch(), color-mix(), and light-dark()
- Typed Custom Properties with @property
- Popovers and Entry Animations
- Anchor Positioning
- View Transitions
- Scroll-Driven Animations
- Small Wins: text-wrap, field-sizing, and More
- Progressive Enhancement and Browser Support
- What You Can Delete
- Common Pitfalls
- Conclusion
Introduction
If you learned CSS before 2022, a lot of what you “know” about its limits is out of date. Many of the reasons we reached for Sass, CSS-in-JS, or a few hundred lines of JavaScript have quietly disappeared:
- Sass nesting is now native CSS
- Media queries that look at the viewport have a component-level counterpart in container queries
- “Parent selectors”, long considered impossible, exist as
:has() - Specificity wars with third-party styles can be settled with cascade layers
- Tooltips and dropdowns that needed Popper.js or Floating UI can be positioned with anchor positioning
- Page transitions that needed an animation library can be done with view transitions
The catch is that these features shipped one at a time over several years, so it’s easy to miss which ones are safe to use and how they fit together. This guide walks through the modern CSS features worth knowing in 2026, with practical examples, browser support notes, and the code each one lets you delete.
If you want background on how to organize styles at scale first, see our CSS architecture guide. This post focuses on what the language itself can now do.
Native CSS Nesting
Nesting was the number one reason many teams kept a preprocessor around. It’s now supported in every major browser (Baseline since 2023):
.card { padding: 1rem; border-radius: 0.75rem; background: var(--surface);
& h2 { font-size: 1.25rem; }
&:hover { box-shadow: 0 4px 16px rgb(0 0 0 / 0.1); }
& + & { margin-top: 1rem; }
@media (width >= 48rem) { padding: 1.5rem; }}A few things to know if you’re coming from Sass:
&is optional before element selectors in current browsers (h2 { ... }works inside.card), but writing&explicitly keeps the intent obvious and works in older engines that required it.- No string concatenation. Sass lets you write
&__titleto produce.card__title. Native nesting does not;&__titleis invalid. BEM users should keep writing full class names. - Specificity follows
:is(). A nested rule behaves like:is(.card) h2, which matters when the parent is a selector list mixing IDs and classes. - Media and container queries can be nested directly inside a rule, which keeps responsive overrides next to the base styles.
/* ❌ Doesn't work in native CSS */.card { &__title { font-weight: 600; }}
/* ✅ Write the full class */.card__title { font-weight: 600;}Also note the (width >= 48rem) syntax above. Range syntax in media queries is Baseline too, and it’s far easier to read than min-width / max-width pairs.
Container Queries
Media queries answer “how wide is the viewport?” But components don’t live in the viewport; they live in sidebars, grids, modals, and cards. A product card might be 300px wide in a three-column grid and 900px wide on a detail page, on the same screen size.
Container queries let a component respond to the size of its container instead.
Size Queries
First, mark an element as a container:
.card-wrapper { container-type: inline-size; container-name: card;}Or use the shorthand:
.card-wrapper { container: card / inline-size;}Then query it:
.product-card { display: grid; gap: 1rem;}
@container card (width >= 30rem) { .product-card { grid-template-columns: 10rem 1fr; }}
@container card (width >= 50rem) { .product-card { grid-template-columns: 16rem 1fr auto; }}Now .product-card switches layouts based on how much room it actually has, wherever you drop it.
Important details:
inline-sizeis almost always what you want.container-type: sizealso tracks height, but it requires the container to have an explicit height, since its contents can no longer size it. That surprises people.- An element can’t query itself. The container is an ancestor; the styles go on its descendants. That’s why you usually need a wrapper element.
- Unnamed queries match the nearest container. Names make intent explicit and avoid accidentally matching an intermediate container.
Container Query Units
Container queries also introduce units relative to the container’s size: cqi (1% of inline size), cqb (block size), plus cqw, cqh, cqmin, and cqmax.
These are great for fluid typography that scales with the component rather than the viewport:
.product-card h2 { /* Scales with the card, clamped to sensible limits */ font-size: clamp(1rem, 4cqi, 1.75rem);}Style Queries
Style queries let you query the computed value of a custom property on the container:
.card-wrapper { container-name: card;}
.card-wrapper[data-variant="featured"] { --variant: featured;}
@container card style(--variant: featured) { .product-card { border: 2px solid var(--accent); }}Style queries on custom properties are supported in Chromium and Safari. Firefox support is still in progress, so treat them as an enhancement for now.
The :has() Selector
:has() matches an element if it contains something matching the selector you pass. It’s usually called the “parent selector,” but it’s more general than that: it lets you style anything based on what’s inside or after it. It’s been Baseline since late 2023.
/* A card that contains an image gets a different layout */.card:has(img) { grid-template-rows: auto 1fr;}
/* A form field wrapper with an invalid input */.field:has(input:user-invalid) { --border-color: var(--danger);}
/* A label followed by a required input */label:has(+ input:required)::after { content: " *"; color: var(--danger);}Note the use of :user-invalid there. Unlike :invalid, it only matches after the user has interacted with the field, so you don’t show errors on an empty form the moment it loads.
Replacing JavaScript State Classes
A lot of JavaScript exists only to toggle a class on an ancestor. :has() removes the need for most of it:
/* Lock page scroll while any modal dialog is open */html:has(dialog[open]) { overflow: hidden;}
/* Theme switch with no JavaScript class toggling */:root:has(#dark-mode:checked) { color-scheme: dark;}
/* Highlight a table row when its checkbox is selected */tr:has(input[type="checkbox"]:checked) { background: var(--selected-bg);}
/* Dim siblings of the hovered item */.grid:has(.item:hover) .item:not(:hover) { opacity: 0.6;}Quantity Queries
:has() combined with :nth-child gives you layouts that adapt to how many children exist:
/* Switch to two columns when the list has 6 or more items */.list:has(> :nth-child(6)) { columns: 2;}Performance Notes
Browsers have optimized :has() heavily, but broad selectors still cost something because every DOM change can trigger re-evaluation. Prefer anchored, specific selectors:
/* ❌ Broad: re-checked against every element on every change */:has(.error) { ... }
/* ✅ Scoped: only checked on .form-group elements */.form-group:has(> .error) { ... }Cascade Layers with @layer
Specificity is the source of most CSS frustration. A third-party library uses .btn.btn-primary, your override uses .button, and you end up with !important or a longer selector. Cascade layers fix this by adding a level to the cascade that’s checked before specificity.
/* Declare the order once, up front. Later layers win. */@layer reset, vendor, base, components, utilities;
@layer reset { *, *::before, *::after { box-sizing: border-box; }}
@layer base { a { color: var(--link); }}
@layer components { .button { background: var(--accent); }}
@layer utilities { .hidden { display: none; }}With this setup, .hidden in utilities beats any selector in components, no matter how specific, because utilities is a later layer.
Taming Third-Party CSS
You can put an entire imported stylesheet in a low-priority layer:
@layer reset, vendor, base, components, utilities;
@import url("some-ui-library.css") layer(vendor);Now every rule in the library, however specific, loses to your base and components layers. No more !important arms race.
Rules Worth Remembering
- Unlayered styles beat all layered styles. This is a common surprise. If you adopt layers incrementally, your legacy unlayered CSS will win over everything in layers.
!importantreverses layer order. An!importantdeclaration inresetbeats an!importantinutilities. This is intentional: it lets low layers protect critical styles.- Layers can be nested (
@layer components.forms { ... }) to organize large codebases.
Tailwind CSS v4 uses native cascade layers internally (theme, base, components, utilities), which is a good sign of how mainstream this has become.
Scoped Styles with @scope
@scope limits styles to a subtree of the DOM, optionally with a lower boundary where the scope stops:
@scope (.card) to (.card-content) { img { border-radius: 0.5rem; }
:scope { padding: 1rem; }}This styles img elements inside .card but not inside a nested .card-content, which is often where arbitrary user or CMS content goes. That “donut scope” is something BEM and CSS Modules can’t express.
@scope also adds scoping proximity to the cascade: when two scoped rules have equal specificity, the one whose scope root is closer to the element wins. That makes nested themes behave the way you’d expect:
@scope (.theme-light) { a { color: navy; }}
@scope (.theme-dark) { a { color: skyblue; }}A link inside .theme-dark nested inside .theme-light gets skyblue, because the dark scope root is closer.
@scope has shipped in Chromium and Safari, and Firefox support arrived more recently. Check current Baseline status for your audience before relying on it for critical styling; CSS Modules or BEM remain a solid fallback.
Modern Color: oklch(), color-mix(), and light-dark()
oklch()
oklch() describes color as lightness, chroma, and hue in a perceptually uniform space. In practice that means changing lightness by 10% looks like the same step regardless of hue, which isn’t true of hsl().
:root { --brand: oklch(62% 0.19 255); --brand-light: oklch(80% 0.1 255); --brand-dark: oklch(45% 0.19 255);}It’s ideal for generating consistent palettes and design tokens. If you’re building a token system, our guide on design systems and design tokens pairs well with this.
Relative Color Syntax
Derive new colors from existing ones without a preprocessor:
.button { background: var(--brand);}
.button:hover { /* Same hue and chroma, 8% lighter */ background: oklch(from var(--brand) calc(l + 0.08) c h);}
.overlay { /* Same color at 50% opacity */ background: oklch(from var(--brand) l c h / 0.5);}color-mix()
.badge { /* 20% brand color mixed into the surface */ background: color-mix(in oklch, var(--brand) 20%, var(--surface));}light-dark()
light-dark() picks a value based on the element’s used color scheme, so you can define both theme values in one place:
:root { color-scheme: light dark;
--surface: light-dark(#ffffff, #121212); --text: light-dark(#1a1a1a, #ededed);}
/* Force a scheme for a subtree or a user toggle */.force-dark { color-scheme: dark;}This replaces the pattern of duplicating every token inside a @media (prefers-color-scheme: dark) block. Note that light-dark() only works for colors.
Typed Custom Properties with @property
Normal custom properties are untyped strings, so the browser can’t animate them. @property registers a custom property with a type, an initial value, and inheritance rules:
@property --angle { syntax: "<angle>"; initial-value: 0deg; inherits: false;}
.spinner { background: conic-gradient(from var(--angle), var(--brand), transparent); animation: spin 1.2s linear infinite;}
@keyframes spin { to { --angle: 360deg; }}Without @property, that animation would jump from start to end. With it, the browser knows --angle is an angle and interpolates smoothly. It’s also useful for animating gradient stops, which previously needed JavaScript.
inherits: false is also a small performance win for properties only used on one element, since the browser doesn’t need to propagate them down the tree.
Popovers and Entry Animations
The Popover API
Menus, tooltips, and toggletips used to require JavaScript for open/close state, outside-click dismissal, Escape key handling, and z-index management. The Popover API handles all of it in HTML:
<button popovertarget="account-menu">Account</button>
<div id="account-menu" popover> <a href="/settings">Settings</a> <a href="/logout">Log out</a></div>You get:
- Top-layer rendering: no more
z-index: 9999, and no clipping byoverflow: hiddenancestors - Light dismiss: clicking outside or pressing Escape closes it (for
popover="auto", the default) - Accessible wiring: the button gets the correct expanded state exposed to assistive technology
Use popover="manual" when you want to control closing yourself, for example for toast notifications.
Animating from display: none
Animating elements that enter or leave the page used to be awkward because display: none can’t be transitioned. Two features fix that:
@starting-styledefines the styles an element transitions from when it first appearstransition-behavior: allow-discretelets discrete properties likedisplayparticipate in transitions
[popover] { opacity: 0; translate: 0 -0.5rem; transition: opacity 0.2s, translate 0.2s, display 0.2s allow-discrete, overlay 0.2s allow-discrete;}
[popover]:popover-open { opacity: 1; translate: 0 0;
@starting-style { opacity: 0; translate: 0 -0.5rem; }}Transitioning display and overlay keeps the popover visible and in the top layer until the exit animation finishes. The same pattern works for <dialog> elements with [open].
Anchor Positioning
Positioning a floating element next to its trigger, and flipping it when it would overflow the viewport, is the whole reason libraries like Popper.js and Floating UI exist. CSS anchor positioning does it natively:
.trigger { anchor-name: --account-trigger;}
#account-menu { position-anchor: --account-trigger; position-area: block-end span-inline-end; margin: 0.25rem 0 0;
/* Flip above the trigger if there's no room below */ position-try-fallbacks: flip-block;}anchor-namenames an element as an anchorposition-anchortells the positioned element which anchor to useposition-areaplaces it on a 3×3 grid around the anchor, which covers most dropdown and tooltip casesposition-try-fallbacksgives the browser alternatives to try when the element would overflow
For finer control, use the anchor() function in inset properties:
.tooltip { position: absolute; position-anchor: --info-icon; bottom: anchor(top); left: anchor(center); translate: -50% -0.5rem;}You can also size elements against their anchor, for example making a dropdown at least as wide as its button with min-width: anchor-size(width).
Combined with the Popover API, you can build a fully accessible, auto-flipping dropdown with zero JavaScript. Anchor positioning was an Interop 2025 focus area and is available in Chromium and Safari, with Firefox support rolling out. Until it’s Baseline for your users, keep a JavaScript fallback using @supports:
@supports not (anchor-name: --x) { /* Simple fallback position, or let Floating UI take over */}View Transitions
View transitions animate between two states of the page. The browser takes a snapshot of the old state, you update the DOM, it snapshots the new state, and then it crossfades (or morphs) between them.
Same-Document Transitions
For SPAs and in-page updates, wrap your DOM change in document.startViewTransition():
function updateView(render: () => void) { // Fallback for browsers without support if (!document.startViewTransition) { render(); return; }
document.startViewTransition(() => render());}By default you get a crossfade. To morph a specific element, give it a view-transition-name in both states:
.product-thumbnail { view-transition-name: product-image;}
/* Customize the animation */::view-transition-old(product-image),::view-transition-new(product-image) { animation-duration: 0.35s;}Each view-transition-name must be unique on the page at the moment of the transition. For lists, set the name dynamically (for example via an inline style or view-transition-name: match-element where supported) only on the item that’s transitioning.
Same-document view transitions are now supported in all major browsers.
Cross-Document Transitions
For multi-page apps, you can opt into transitions between full page navigations with a single rule on both pages:
@view-transition { navigation: auto;}This works for same-origin navigations and gives a static site an app-like feel with no client-side router. Frameworks like Astro already lean on this. Cross-document transitions are supported in Chromium and Safari; other browsers simply navigate normally, which makes it a perfect progressive enhancement.
Respect Reduced Motion
Always tone down transitions for users who ask for it:
@media (prefers-reduced-motion: reduce) { ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; }}See our web accessibility guide for more on motion and other user preferences.
Scroll-Driven Animations
Scroll-driven animations link a CSS animation’s progress to scroll position instead of time. Reading progress bars, parallax effects, and reveal-on-scroll used to need scroll listeners or IntersectionObserver.
/* Reading progress bar tied to page scroll */.progress-bar { position: fixed; inset: 0 0 auto 0; height: 4px; background: var(--brand); transform-origin: left; animation: grow linear; animation-timeline: scroll(root);}
@keyframes grow { from { transform: scaleX(0); } to { transform: scaleX(1); }}/* Fade elements in as they enter the viewport */.reveal { animation: fade-in linear both; animation-timeline: view(); animation-range: entry 0% cover 30%;}
@keyframes fade-in { from { opacity: 0; translate: 0 2rem; } to { opacity: 1; translate: 0 0; }}Because these run on the compositor when you animate transform and opacity, they’re smoother than scroll-listener JavaScript, which runs on the main thread. That directly helps INP, as covered in our Core Web Vitals guide.
Support is in Chromium and Safari, with Firefox still working on it. Wrap these in @supports (animation-timeline: view()) so unsupported browsers show the final state instead of invisible content.
Small Wins: text-wrap, field-sizing, and More
Not every modern feature is a big architectural change. These small ones remove a surprising amount of friction:
/* Balanced line lengths for headings: no more orphaned single words */h1,h2,h3 { text-wrap: balance;}
/* Better rag for body text, avoiding short last lines */p { text-wrap: pretty;}
/* Textareas that grow with their content (Chromium) */textarea { field-sizing: content; min-height: 3lh;}
/* Animate to and from height: auto (Chromium) */:root { interpolate-size: allow-keywords;}
/* Consistent form control accent color */:root { accent-color: var(--brand);}
/* Prevent scroll chaining from modals into the page */.modal-body { overscroll-behavior: contain;}The lh unit used above equals the element’s line height, so 3lh means “three lines tall.” It’s handy for sizing anything text-related.
text-wrap: balance is Baseline, while pretty, field-sizing, and interpolate-size are not yet supported everywhere. All of them degrade gracefully: unsupported browsers just use the default behavior.
Progressive Enhancement and Browser Support
Not every feature in this guide is equally safe. Here’s a practical summary as of mid-2026:
| Feature | Status | Fallback strategy |
|---|---|---|
| Nesting | Baseline | None needed |
| Container size queries | Baseline | None needed |
:has() | Baseline | None needed |
@layer | Baseline | None needed |
oklch(), color-mix() | Baseline | None needed |
light-dark() | Baseline | None needed |
@property | Baseline | Animation snaps instead of tweening |
Popover + @starting-style | Baseline | None needed |
| Same-document view transitions | All major browsers | Feature-detect in JavaScript |
@scope | Recently in all engines | BEM or CSS Modules |
| Container style queries | Chromium, Safari | Use classes or data attributes |
| Anchor positioning | Chromium, Safari; Firefox rolling out | @supports + Floating UI |
| Cross-document view transitions | Chromium, Safari | Normal navigation |
| Scroll-driven animations | Chromium, Safari | @supports, show final state |
field-sizing, interpolate-size | Chromium | Default behavior |
Browser support changes quickly, so verify against Baseline or MDN’s compatibility tables before shipping anything that isn’t marked Baseline.
Feature Detection
@supports works for properties, values, and selectors:
@supports (container-type: inline-size) { ... }
@supports selector(:has(a)) { ... }
@supports (anchor-name: --x) { ... }And in JavaScript:
const supportsAnchors = CSS.supports("anchor-name", "--x");const supportsViewTransitions = "startViewTransition" in document;The general rule: if the fallback is “slightly less polished,” ship the feature now. If the fallback is “broken layout” or “invisible content,” gate it behind @supports.
What You Can Delete
Here’s where modern CSS pays for itself. Common code that these features replace:
| You used to write | Now use |
|---|---|
| Sass for nesting | Native nesting |
Sass lighten() / darken() / rgba() helpers | Relative color syntax, color-mix() |
ResizeObserver to toggle component layout classes | Container queries |
| JavaScript to add classes to parent elements | :has() |
!important to beat library styles | @layer |
| Popper.js / Floating UI for dropdowns | Anchor positioning |
| Click-outside and Escape handlers for menus | Popover API |
| Duplicated dark-mode token blocks | light-dark() |
| Scroll listeners for progress bars and reveals | Scroll-driven animations |
| Animation libraries for page transitions | View transitions |
| Auto-growing textarea scripts | field-sizing: content |
Every line of JavaScript you remove is a line that doesn’t need to be downloaded, parsed, or run on the main thread. CSS features are also declarative, which means fewer edge cases around timing, cleanup, and server rendering. If you’re working in a framework with server components, moving interactivity into CSS can even let you keep a component on the server entirely.
Common Pitfalls
Expecting an Element to Query Its Own Container
/* ❌ The container can't respond to its own size */.card { container-type: inline-size;}
@container (width >= 30rem) { .card { padding: 2rem; }}
/* ✅ Query from a child, or add a wrapper */@container (width >= 30rem) { .card > .card-body { padding: 2rem; }}Using container-type: size Without a Height
container-type: size applies size containment in both directions, so the container’s height no longer depends on its content. Without an explicit height, it collapses to zero. Use inline-size unless you specifically need to query height.
Leaving Legacy CSS Unlayered
When you introduce @layer into an existing codebase, all your old unlayered CSS automatically beats everything in layers. Either wrap legacy styles in a layer of their own (@import url("legacy.css") layer(legacy);), or adopt layers starting from your highest-priority code.
Duplicate view-transition-name Values
If two visible elements share a view-transition-name when the transition starts, the transition is skipped. In lists, assign the name only to the element being transitioned.
Hiding Content Behind Unsupported Animations
/* ❌ In browsers without scroll timelines, content stays at opacity: 0 */.reveal { opacity: 0; animation: fade-in linear forwards; animation-timeline: view();}
/* ✅ Only apply the hidden starting state when supported */@supports (animation-timeline: view()) { .reveal { animation: fade-in linear both; animation-timeline: view(); }}Overusing :has() on Broad Selectors
body:has(...) and unanchored :has() selectors are re-evaluated frequently. They’re fine for occasional state like an open dialog, but avoid using them for high-frequency changes like hover across large lists.
Conclusion
CSS in 2026 is a different language than the one many of us learned. It has nesting, component-level responsiveness, relational selectors, cascade control, real color science, and native solutions for positioning, overlays, and transitions. Most of it is supported everywhere, and the rest degrades gracefully.
Key Takeaways:
- Nesting, container queries,
:has(), and@layerare Baseline. You can use them in production today without fallbacks - Container queries make components truly reusable by responding to their own space, not the viewport
:has()replaces a lot of JavaScript that only existed to toggle classes on ancestors- Cascade layers end specificity wars, especially with third-party CSS
- Popovers, anchor positioning, and view transitions replace whole libraries, but check support and use
@supportswhere the fallback matters - Modern color functions like
oklch(),color-mix(), andlight-dark()remove most reasons to keep a preprocessor for theming
Next Steps:
- Search your codebase for
ResizeObserverand class-toggling JavaScript, and see which can become container queries or:has() - Wrap your third-party CSS in a
vendorlayer and remove the!importantoverrides - Replace one dropdown with the Popover API plus anchor positioning, with a
@supportsfallback - Add
@view-transition { navigation: auto; }to a multi-page site and see how it feels
Happy styling! 🎨