Can we have custom media queries, please?
- 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?
Join 5.5k readers and learn something new every week with Web Weekly.