DEV Community

Stefan Judis
Stefan Judis

Posted on • Originally published at stefanjudis.com

Can we have custom media queries, please?

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 and wanted to use 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)) {
}

Enter fullscreen mode Exit fullscreen mode

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!

But here's the solution – say hello to custom media queries!

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

@media (--narrow-window) {
  /* narrow window styles */
}
Enter fullscreen mode Exit fullscreen mode

Isn't this beautiful? I think many web developers are waiting for that 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 for a few minutes, and apparently, custom media queries are in the spec for years. There doesn't seem to be much interest in implementing it, though. Neither MDN nor caniuse.com knows about the feature. :/

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?

Top comments (0)