Use Sass to create better media queries
Sass, if you’ve never heard of it, is a preprocessor scripting language for CSS. Preprocessor? Scripting? What does that mean? Well, basically it extends CSS and allows you to use functions, loop through lists, set variables, use conditional statements, and a bunch of other handy features. It does all this and then converts everything into a single .css file for your project to read. For this blog post I’ll be covering how to quickly create CSS media queries, perfect for responsive design and layouts, with the Sass @mixin, @include, and @content at-rules. With Sass you can use two different file types, .scss and .sass, I’ll be using .scss for this post.
Making media queries in CSS can be a time consuming process. Laying out the individual rules can be time consuming and breaks up your code. Its annoying to have to search in your CSS files for specific elements right? Well Sass introduces a couple of great features to address this.
First off, with nesting you’re allowed to create the media queries directly inside of the CSS selector you’re working on!
But, as you can see we’re still writing out media queries directly and it seems awfully repetitive… Wouldn’t it be nice if we could create functions to programmatically make this code more D.R.Y. ( Don’t Repeat Yourself ) ?
Well we can create a mixin (think of this like a JavaScript function) and include it into our styling directly! Lets make two, one for a tablet view and one for a mobile view.
This definitely helps. We could combine styles that work for multiple elements into a single mixin and import it them.
Wait… Hold on…
Doesn’t this just get us back to our original problem? Our stylings are now split up again. You can imagine for a large project that this could become annoying again. I thought Sass was here to solve that problem?
Here's the solution, we use the @content at-rule to solve this! By updating our media query to contain @content and specifying the styles we want in brackets we tell the mixin to use those styles as the content of the media query.
This is great! Now we can just send along whatever styles we need for our different views. This technique has a downside though. We’re hardcoding each of our widths into the media queries. What if we needed a separate media query for a specific size not included here? We’d have to make another mixin with a media query.
The solution here is to pass along the width that you need as an argument to the mixin and set the max-width of the media query from that value.
Awesome! Now we have a flexible mixin that can be used anywhere! Just pass along the width you need and write the styles in between the brackets!
If you’d like to learn more about how to use Sass check out the documentation here .