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 (CSS variables) 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)) {

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 */

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

Source link