BLACKBELT

CSS Front-End Development SASS

Authored by Dustin Horton

2 Comments

Flexible & Robust Media Queries in Sass

Thanks to many articles that covered the ‘content’ feature of Sass 3.2, such as the one from The Sass Way, the following has become somewhat of a standard for doing media queries in Sass:

This approach works fine, but I’ve recently moved away from it to something a bit more flexible and terse.

Of note, I’m actually passing the variable right through to the media query, as opposed to naming it a second time as in the first code sample. An added bonus: I can use the mixin & pass a pixel value straight in without the need for a separate mixin. So both of these usages are valid:

This takes care of 95% of my needs, but here’s what I actually use in nearly every project to meet the demands of the remaining 5%.

I could roll them all into a single mixin, but I always prefer longer mixins to longer includes, since I’m continually writing the includes and rarely touching the mixins.

I use quite a few more variables in practice. ‘Full’ refers to the full width of a design; that is, whatever width the site stops/starts scaling at, if such a width exists. Other then that, they’re all roughly device based.

The first mixin is a more robust version of the previous media query. The first condition is a Webkit query, which I use for separately styling select, radio & checkbox form elements in Webkit browsers without it bleeding over to Firefox or IE which are less customizable and therefore worth leaving alone in my opinion. The second condition is a retina/hi-dpi query, for serving 2x assets. The last condition is the normal max-width query.

The other three mixins are: min-width, max-height & min-height. Self-explanatory, and very simple to use.

The only downside I’ve found with this method is the media queries will fail silently; that is, if you pass in a variable that doesn’t exist, the styles will still compile, but with a malformed media query selector. But having a shorter mixin & being able to pass pixels values directly in is very worth the trade off for me.