Published at
Updated at
Reading time
2min

You know the problem: you want to reuse custom properties in media queries but can't.

:root {
  --width: 20em;
}

/* this doesn't work :/ */
@media (min-width: var(--width)) {
}

I discovered the solution to this problem a while ago — custom media queries.

/* this isn't supported anywhere */
@custom-media --narrow-window (max-width: 30em);

@media (--narrow-window) {
  /* narrow window styles */
}

Unfortunately, as far as I know, custom media queries have never been implemented anywhere. Bummer.

However, the CSS evolution is still in full swing, and we have CSS features we couldn't even dream of years ago. :has(), native CSS nesting and container queries are ready to use.

With container queries, custom property style queries are slowly becoming a thing.

MDN Compat Data (source)
Browser support info for Style queries for custom properties
chromechrome_androidedgefirefoxfirefox_androidsafarisafari_iossamsunginternet_androidwebview_android
111111111NopeNein181822.0111

Could we use custom properties to formalize variables in media / container queries? Here's Jared White doing just that.

:root {
  --is-mobile: false;

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

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;
  }
}

The style query approach is somewhat different than custom media queries, but it does the job. And if style queries for custom properties ship across browsers, we can call it for custom media queries.

They were a nice idea, but if a media / container query mix allows me to toggle and reuse custom properties based on viewport width, that does the trick for me.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles