{"id":374670,"date":"2022-10-31T06:05:38","date_gmt":"2022-10-31T13:05:38","guid":{"rendered":"https:\/\/css-tricks.com\/?p=374670"},"modified":"2022-10-31T06:05:39","modified_gmt":"2022-10-31T13:05:39","slug":"the-new-css-media-query-range-syntax","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/the-new-css-media-query-range-syntax\/","title":{"rendered":"The New CSS Media Query Range Syntax"},"content":{"rendered":"\n

We rely on CSS Media Queries<\/a> for selecting and styling elements based on a targeted condition. That condition can be all kinds of things but typically fall into two camps: (1) the type of media that\u2019s being used, and (2) a specific feature of the browser, device, or even the user\u2019s environment.<\/p>\n\n\n\n

So, say we want to apply certain CSS styling to a printed document:<\/p>\n\n\n\n

@media print {\n  .element {\n    \/* Style away! *\/\n  }\n}<\/code><\/pre>\n\n\n\n

The fact that we can apply styles at a certain viewport width has made CSS Media Queries a core ingredient of responsive web design since Ethan Marcotte coined the term<\/a>. If the browser\u2019s viewport width is a certain size, then apply a set of style rules, which allows us to design elements that respond to the size of the browser.<\/p>\n\n\n\n

\/* When the viewport width is at least 30em... *\/\n@media screen and (min-width: 30em) {\n  .element {\n    \/* Style away! *\/\n  }\n}<\/code><\/pre>\n\n\n\n

Notice the and<\/code> in there? That\u2019s an operator that allows us to combine statements. In that example, we combined a condition that the media type is a screen<\/code> and that it\u2019s min-width<\/code> feature is set to 30em<\/code> (or above). We can do the same thing to target a range of viewport sizes:<\/p>\n\n\n\n

\/* When the viewport width is between 30em - 80em *\/\n@media screen and (min-width: 30em) and (max-width: 80em) {\n  .element {\n    \/* Style away! *\/\n  }\n}<\/code><\/pre>\n\n\n\n

Now those styles apply to an explicit range of viewport widths rather than a single width!<\/p>\n\n\n\n

But the Media Queries Level 4 specification has introduced a new syntax for targeting a range of viewport widths using common mathematical comparison operators \u2014 things like <<\/code>, ><\/code>, and =<\/code> \u2014 that make more sense syntactically while writing less code.<\/p>\n\n\n\n

Let\u2019s dig into how that works.<\/p>\n\n\n\n\n\n\n

New comparison operators<\/h3>\n\n\n

That last example is a good illustration of how we\u2019ve sort of \u201cfaked\u201d ranges by combining conditions using the and<\/code> operator. The big change in the Media Queries Level 4 specification is that we have new operators that compare values rather than combining them:<\/p>\n\n\n\n