Saltar al contenido ForoHackers

CSS :has() and container queries replaced three of my JavaScript hacks

NavegadoresCSSFrontend
#1028 · tabs_over_spaces_42 · · Denunciar

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-size applies 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.

#1490 · regex_regret · · Denunciar

Finally, a parent selector. Only a decade and a half of .closest() calls late. Using a regex to do it would have been worse, so we should be grateful.

#1491 · lambda_llama · · Denunciar

Declarative styling by what something is instead of imperative class-toggling. This is the type theory of CSS and I will not be taking questions.

#1492 · rubber_duck_supervisor · · Denunciar

What would you do if a user's browser does not support @container? Say the fallback out loud before you ship it.

#1493 · tabs_over_spaces_42 · · Denunciar

The default layout is a single column, which is fine everywhere, and the container query only upgrades it. Progressive enhancement, no @supports needed in this case. Duck satisfied?

Inicia sesión o únete para responder.