Add Superpowers to Your CSS Variables with Style Queries

We’re on the verge of yet another CSS revolution with the arrival of style queries. If you’ve ever thought:

Yeah, variables are cool and all, but it’s a bummer I can only use them to set one property at a time

or

Wow, I wish I could style this whole layout differently based on a CSS variable I set with a media query

…then your dreams are about to come true!

Style container queries were first added to Chromium browsers last year, and now they’re landing in Safari with the arrival of Safari Technology Preview 190. The syntax is very simple to use, even simpler than container queries based on size:

@container style(--my-var: 123) {
  section > .do_stuff > [here] {
    color: yellow;
    background: maroon;
  }
}

In case it’s not obvious, the style rules above will only apply if there’s a --my-var custom property set to the value of 123. 🤯

The spec for style queries allows for the querying of any computed styles, not just variables, but browser engines are focusing on variables first because, frankly, it’s a whole lot easier. And honestly? It’s also the absolute coolest.

Because now we can set theme and breakpoint type variables and use those to style all sorts of things! Imagine a world where you can do this:

:root {
  --is-mobile: false;

  @media (max-width: 500px) {
    --is-mobile: true;
  }
}

Previously, there wasn’t anything you could “do” with a variable such as this, because false and true don’t apply meaningfully to any particular style rules. But now with style queries, you can do this:

aside.sidebar {
  font-size: 1.5rem;
  line-height: 1.5;
  font-weight: 600;
}

@container style(--is-mobile: true) {
  aside.sidebar {
    font-size: 1.1rem;
    line-height: 1.25;
    font-weight: 500;
  }
}

And if you’re thinking to yourself: wait a minute, isn’t this kind of like if we could use CSS variables directly in media queries? …the answer is, yes, it kind of is. 🙌

You can also “theme” components and then “untheme” them later simply by changing the value of a custom property. Here’s a CodePen demonstrating how a button is themed orange higher up in the DOM tree, and then lower in the tree that theme is switched off. It’s almost like “scoped CSS” but controlled at the level of page authoring, not component authoring.

We’re just scratching the surface of what’s enabled by style queries. The only fly in the ointment is that Firefox hasn’t started work on this feature yet. Keep a close eye on this Bugzilla issue and cross your fingers we see activity soon. In the meantime, I could envision some possible light usage of style queries in a “progressive enhancement” sort of way once production support is available across Chromium and Safari. Thrilling!

Skip to content