The Ultimate Media Query Mixin

If you’re building for the web, you’re (most likely) using media queries to control layout reflows in a responsive environment. If you’re using Sass, you’re probably using a mixin to handle your media queries. There are a ton of awesome mixins out there to handle media queries, but none of them really worked for me in all cases. I’ve found that a lot of them have predefined breakpoints, or the only options are for min- and max-width. Sometimes I need a little more flexibility, so I set out to write my own:

See the Pen Media Query Mixin by Pralie (@praliedutzel) on CodePen.20669

This is actually pretty simple: pull all arguments into an associative map, loop through them, and append them to the media query if a value was entered. The mixin currently accepts arguments for min- and max-width, device-pixel-ratio, orientation, and min- and max-height, since these are the features I use most often. There’s also an argument for the media type, which defaults to screen.

The Pros

Flexibility and ease of use are the two big ones. I’m able to use the mixin in a variety of ways and only include the arguments I need. Because there is no config to define your breakpoints, you can add whatever you want. Personally, I keep all my breakpoint variables stored in a config partial so I can use them for other things like max-width.

The Cons

Despite trying to make this flexible, the output isn’t as flexible as some may need. The options for arguments are set in the mixin, so if you wanted another option, you would need to add it into the arguments list and $breakpoints map yourself. Comma-separated lists can’t be output with the current mixin, which could be a drawback for some looking for more robust media queries.


Okay, so maybe “ultimate” wasn’t the right word, but for me, this is my go-to mixin for media queries. I’ve used this on every website I’ve built with Sass for the last year or so. It’s gone through a lot of live tests and tweaks until it’s gotten to a point where I’m happy with it. If you have any suggestions for improvements, feel free to let me know on Twitter!

If you have comments or questions, you can always reach me via Twitter. Thanks for reading!
Posted on December 14, 2015 in Sass.