Published at
Updated at
Reading time
2min

Before you read about custom media queries, container style queries will likely make them obsolete.

Today I discovered an exciting section in the CSS media queries Level 5 spec. The custom media queries section explains how to define and reuse aliases for media queries. Why would you need that?

Well... if you're using CSS custom properties (CSS variables) and wanted to reference them in a media query, you probably discovered that you can't use custom properties in this context. CSS custom properties weren't designed for that use case. Bummer!

:root {
  --width: 20em;
}

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

You could now rely on tools such as Sass and introduce another non-native variable system to clean up your media queries, but yeah... this approach is not great!

Here's the solution โ€“ say hello to custom media queries!

@custom-media --narrow-window (max-width: 30em);

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

Isn't this syntax beautiful? I bet many web developers are waiting for variables in media queries for quite some time. But here's the sad news: you can't use custom media queries today because it's only future music.

I googled around, and apparently, custom media queries are in the spec for years, but there doesn't seem to be much interest in implementing them. Neither MDN nor caniuse.com knows about the feature, yet. :/

If you want to use it today, leverage PostCSS and the Custom Media plugin. That's better than nothing, but hey... can we have custom media queries, please?

Edits and comments

  1. Adam Argyle filed a Chromium feature request for it now. ๐ŸŽ‰ You can give your vote here.

  2. Marco Biedermann pointed out that custom media queries are part of the postcss-present-env stage 1.

  3. Rachel Andrew pointed out that MDN only includes features that are supported in at least one browser.

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