New syntax for range media queries

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.

Source

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) {
  // Styles for viewports with a width of 400 pixels or greater.
}

The new syntax allows for the use of a comparison operator:

@media (width >= 400px) {
  // Styles for viewports with a width of 400 pixels or greater.
}

Testing for a maximum width:

@media (max-width: 30em) {
  // Styles for viewports with a width of 30em or less.
}

And, the version using the level 4 syntax:

@media (width <= 30em) {
  // Styles for viewports with a width of 30em or less.
}

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) {
  // Styles for viewports between 400px and 600px.
}

This can be rewritten in the new syntax as:

@media (400px <= width <= 600px )  {
  // Styles for viewports between 400px and 600px.
}

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.