DEV Community

KAMAL KISHOR
KAMAL KISHOR

Posted on

A new way to write media queries is coming to CSS: range ...

Certainly! Let's dive into the world of CSS Media Queries and explore how they enhance responsive web design.

Understanding CSS Media Queries

CSS Media Queries allow us to adapt the presentation of content based on different viewport sizes. The viewport represents the visible area of a web page, which varies depending on the device used to access the site¹. These queries are essential for creating responsive designs that look great on various screens.

Traditional Syntax

In the past, we used the following syntax to apply styles based on viewport width:

/* When the viewport width is at least 600px */
@media (min-width: 600px) {
  .element {
    /* Style away! */
  }
}
Enter fullscreen mode Exit fullscreen mode

The New Syntax

The Media Queries Level 4 specification introduces a more concise and intuitive syntax using comparison operators. These operators allow us to directly compare values instead of combining conditions with the and operator¹:

  • <: Evaluates if a value is less than another value.
  • >: Evaluates if a value is greater than another value.
  • =: Evaluates if a value is equal to another value.
  • <=: Evaluates if a value is less than or equal to another value.
  • >=: Evaluates if a value is greater than or equal to another value.

Now, let's rewrite the previous example using the new syntax:

/* When the viewport width is 600px or greater */
@media (width >= 600px) {
  .element {
    /* Style away! */
  }
}
Enter fullscreen mode Exit fullscreen mode

Targeting Ranges

Often, we create breakpoints in our designs—conditions where the layout "breaks" and specific styles are applied. These breakpoints typically depend on the viewport being between two widths. With the new syntax, we can easily target a range of viewport widths:

/* When the viewport width is between 600px and 1200px */
@media (width >= 600px) and (width <= 1200px) {
  .element {
    /* Style away! */
  }
}
Enter fullscreen mode Exit fullscreen mode

By embracing these new comparison operators, we can write cleaner, more expressive media queries for responsive web design. Happy coding! 🚀🎨

Top comments (0)