The death of custom media queries
- 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.
111 | 111 | 111 | Nope | Nein | 18 | 18 | 22.0 | 111 |
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.
Join 5.5k readers and learn something new every week with Web Weekly.