Better conditionals in CSS media queries with Range Syntax
The newest version of Chrome, i.e. Chrom 104, has recently been released and with this release, Chrome has become another browser that supports the new range syntax for media queries and this is pretty exciting news if you ask me.
So, if you’re like me who always gets confused while writing media queries that involve the viewport’s width in terms of min-width
and max-width
, the range syntax can help simplify these kinds of media queries.
The new range syntax
For instance, let’s say we have the following media query that checks whether the width of the viewport is between 500px
and 800px
and sets the background of the <body>
to lightpink
, here’s how we were used to writing the media query until now.
@media screen and ((max-width: 800px) and (min-width: 500px)) {
body {
background-color: lightpink;
}
}
Now, with the introduction of the range syntax, the same media query can be rewritten like so.
@media screen and (500px <= width <= 800px) {
body {
background-color: lightpink;
}
}
As you can tell, the condition has become easier to read since we are now able to use comparison operators and instead of using min-width
and max-width
, we can now use the width
to perform the comparison.
Using and
, not
, and or
If you want to make the previous example even more readable, you can also use full boolean algebra with and
, not
, and or
like so.
@media screen and ((width >= 500px) and (width <= 800px)) {
body {
background-color: lightpink;
}
}
Note: it’s important to wrap individual conditions into parentheses when using
and
,not
, andor
.
The demo
I have put together a demo for this where you can see the range syntax in action (Of course, in supported browsers). Try changing the width of the viewport to watch the colors change.
See the Pen Media Query Range Syntax by Amit Merchant (@amit_merchant) on CodePen.
How’s the support?
The support for range syntax has been catching up in browsers steadily. Firefox has been supporting it for quite a while and Chrome has joined the list now. And hopefully, the rest of the browsers will support it soon!
But if you still want to use the range syntax in browsers that don’t support it yet, you can use this PostCSS plugin that will rewrite the new syntax to the old in your stylesheets.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.