Sass Reference
Article

Enhanced Media Queries

By Hugo Giraudel

Media queries are not new to the CSS world. In the old times, we mostly used them to define print-specific styles, but when the specifications (and the browsers) evolved to include advanced queries such as min-width and max-width, they started getting really popular.

You might be pleased to know that they behave in Sass just like they do in plain CSS, with a few extra capabilities though.

Nested media queries

For starters, they can be nested within CSS rules. When a @media block appears within a CSS rule, it bubbles up to the root level, wrapping all selectors from the said rule along the way. For instance:

.foo {
  color: red;

  @media (min-width: 42em) {
    color: blue;
  }
}

This Sass snippet will be compiled into:

.foo {
  color: red;
}

@media (min-width: 42em) {
  .foo {
    color: blue;
  }
}

This feature is very handy when building re-usable components as they can contain styles for any breakpoint and media. It makes it very easy to add media-specific styles without having to repeat selectors or break the flow of the stylesheet.

The other interesting feature of enhanced media queries is that they can also be nested within one another, resulting in a single multi-components media query. Take the following code snippet for example:

@media (min-width: 42em) {
  .foo {
    color: red;

    @media (max-width: 50em) {
      color: blue;
    }
  }
}

The first rule will be output as-is, although the second one will be printed in a new media query formed from the first part and the second part using the and operator:

@media (min-width: 42em) {
  .foo {
    color: red;
  }
}

@media (min-width: 42em) and (max-width: 50em) {
  .foo {
    color: blue;
  }
}

Media queries and SassScript expressions

Of course, media queries can contain SassScript expressions such as variables and functions.

Now, if a variable is used as part of a feature name or feature value, it does not have to be escaped because it lives inside a pair of parentheses, which is an indicator for Sass that the content must be evaluated as SassScript.

$feature: min-width;
$value: 42em;

@media ($feature: $value) {
  .foo {
    color: red;
  }
}

However, if a variable is being used as an expression, it must be escaped.

$media: print;

@media #{$media} {
  .foo {
    color: red;
  }
}

Engine compatibility

Enhanced media queries are fully compatible across all Sass engines and there is no known bug to this day about their implementation.