Tasty media queries in Sass29 May, 2014
Writing and maintaining media queries has become a snap since version 3.2 of Sass. This was the release that debuted
@content, which lets us pass custom styles to mixin inclusions.
This made writing media queries much easier because we could define mixins for smaller-than-n and larger-than-n. These mixins act as filters that let us easily add width, height or resolution specific styles to definitions. The mixin accepts any styles defined within the content of the
@include and adds them into a media query based on the value specified in the argument. For example, with the following mixins:
We could write
Which outputs this CSS
We could take this one step further and use variables for each device breakpoint, making our code more DRY-friendly.
(You can read more about this technique on the Sass blog)
The problem is, until now we’ve had to define our
larger-than mixins with a set of if/else if statements to transform our device argument into a value that Sass can use to create a media query. This quickly gets unwieldy, as each new breakpoint means updating both our mixins with a new statement.
The good news is Sass 3.3 includes full support for maps (aka hashes or data objects), which makes writing media queries even easier. Now we can declare all our breakpoints in one variable:
And use the new
map-get function to access the values. That lets us whittle our mixins down to
We can even write a ‘between’ mixin
Which makes our media queries highly readable
By separating values and mixins using the above technique you can easily add, remove and edit breakpoints in one place. Your code becomes more readable and more maintainable as a result, and you go home with some serious internet points.