New syntax for range media queries
Stay organized with collections
Save and categorize content based on your preferences.
Find out how this new syntax can streamline media queries.
Media Queries enabled responsive design, and the range features that enable testing the minimum and maximum size of the viewport are used by around 80% of sites that use media queries. The Media Queries Level 4 specification includes an improved syntax for these range queries.
Browser Support
- Chrome: 104.
- Edge: 104.
- Firefox: 102.
- Safari: 16.4.
The following examples show how it can streamline your queries.
A typical media query testing for a minimum viewport width, would be written as follows:
@media(min-width:400px){
//Stylesforviewportswithawidthof400pixelsorgreater.
}
The new syntax allows for the use of a comparison operator:
@media(width>=400px){
//Stylesforviewportswithawidthof400pixelsorgreater.
}
Testing for a maximum width:
@media(max-width:30em){
//Stylesforviewportswithawidthof30emorless.
}
And, the version using the level 4 syntax:
@media(width<=30em){
//Stylesforviewportswithawidthof30emorless.
}
This syntax has the potential to streamline queries, in particular when testing between two widths. In the following example, the media query tests for a viewport with a minimum width of 400px, and a maximum width of 600px.
@media(min-width:400px)and(max-width:600px){
//Stylesforviewportsbetween400pxand600px.
}
This can be rewritten in the new syntax as:
@media(400px<=width<=600px){
//Stylesforviewportsbetween400pxand600px.
}
The feature that you are testing, in this case width, goes between the two values.
In addition to making media queries less verbose, the new syntax has the advantage of accuracy. The min- and max- queries are inclusive of the specified values, for example min-width: 400px tests for a width of 400px or greater. The new syntax lets you be more explicit about what you mean and avoid the potential of clashing queries.
To use the new range syntax while accounting for browsers that have not yet implemented it, there is a PostCSS plugin that will rewrite the new syntax to the old in your stylesheets.