Two CSS features that are now widely supported in browsers, and that deleted some code from my projects.
:has(), the "parent selector". Style an element based on what it contains:
.card:has(img) {
display: grid;
grid-template-columns: 8rem 1fr;
}
.card:not(:has(img)) {
padding-inline: 2rem;
}
Before, I added a class with-image from JavaScript. Now the CSS knows by itself.
Container queries: style a component by the width of its container, not the viewport.
.sidebar { container-type: inline-size; }
@container (min-width: 30rem) {
.widget { display: flex; gap: 1rem; }
}
The same .widget can be narrow in a sidebar and wide in the main column without a single media query tied to the page layout.
Gotchas:
container-type: inline-sizeapplies containment, so the container cannot size itself from its children's width. Surprising the first time.:has()with a complex argument can be slow on huge DOMs. Keep it simple and measure.- Always provide a sensible fallback layout for the case where the feature is missing.
Yes, I used to be a "just add a class" person. I am told that was wrong of me.