Modern CSS: :has(), container queries and layers
CSS has changed more since 2022 than in the previous decade. These features are supported in all modern browsers, and they replace JavaScript hacks and fragile workarounds.
:has(): the "parent selector"
For 20 years, CSS couldn't select an element based on what's inside it. Now it can.
:has() can also look at siblings: h2:has(+ p) matches an h2 that is directly followed by a p.
Container queries
Media queries respond to the viewport. Container queries respond to the size of a component's container, so the same card can be compact in a sidebar and spacious in the main column.
There are also container query units: cqi is 1% of the container's inline size, so font-size: clamp(1rem, 4cqi, 2rem).
Cascade layers: @layer
Specificity wars happen when third-party CSS, resets and your components fight. Layers let you decide the priority order explicitly. Later layers always win, whatever the specificity.
Unlayered styles beat every layer, which makes layers perfect for wrapping framework CSS: @import url(bootstrap.css) layer(framework);
Other modern features worth knowing
| Feature | Replaces |
|---|---|
:has() |
JavaScript that adds classes to parent elements |
| Container queries | Component-level JS resize observers |
@layer |
!important and specificity hacks |
| Nesting | Sass, for basic nesting |
color-mix() |
Sass colour functions |
aspect-ratio |
The padding-top percentage hack |
<dialog> / popover + :popover-open |
Modal and tooltip libraries |
| View Transitions API | Complex page-transition JavaScript |
@starting-style |
JS tricks to animate elements as they appear |
Check support on caniuse.com before relying on the newest features, and use @supports for fallbacks:
@supports not (container-type: inline-size) {
.profile { grid-template-columns: auto 1fr; }
}🎓 CSS track complete!
You've gone from selectors to the cutting edge. Combined with the HTML track, you can now build professional, responsive, accessible interfaces. Next, add interactivity with the JavaScript track, or learn Git to save and share your work.
Practice
Build a "settings card" that:
- Uses
:has()to highlight the card when its toggle checkbox is on. - Uses a container query to switch from stacked to side-by-side when the card is wider than 400px.
- Defines its styles inside
@layer components, with a.hiddenutility in a later@layer utilities.
1.What does .card:has(img) select?
2.Container queries respond to…