Media Queries

A media query is a CSS3 module which allows content to render and adapt to conditions such as screen resolution. For example:

@media (max-width: 599px) {

font-size: 1rem;

}

Here we’ve set the font size to 1rem when the viewport size is <= 599px.

Simple enough, and of course we’ll need multiple media queries to have a fully responsive site. However, inevitably the time will come where we’ll need to edit the rules for the actual breakpoints. And searching through all of your code to change every line effected by a rule change is far from ideal. There has to be a better way!

Modern layout specifications have improved greatly over the past few years, Grid and Flexbox are responsive by default. This helps us to cut down on the amount of media queries required in our projects & makes for cleaner code. However, media queries still have a place in modern web development. And as our projects grow bigger, we need a method to manage them. Enter Sass mixins!

Mixins

Sass mixins give us the ability to create reusable chunks of code — they reduce repetition, promote dry code & allow for ease of maintenance. Writing media queries as mixins to inject into your stylesheets, wherever they’re required — makes a whole lot of sense! Lets take a look at an example..

Setup your mixins

Here we’ve written up 5 common breakpoints into @mixin blocks. Note @content is a directive of Sass which allows for the insertion of content later on. If you’re unsure of where to put this code in your folder structure, see Structuring your Sass Projects.

Using a mixin

Say we want to use a mixin to reduce the font size of our header text on mobile devices. We add the mixin as an include, like so:

.header-title {

font-size: 2rem;



@include for-phone-only {

font-size: 1rem;

}

}

When we compile our project, our @include will translate into:

@media (max-width: 599px) {

font-size: 1rem;

}

We now have the ability to easily insert our media queries wherever we like throughout our projects. We don’t need to memorize breakpoints as we have them pre-defined. If we need to alter them we can simply edit the mixins.

Another way to setup our mixins

If you want to take it a step further you could use conditionals to setup your mixins. You create just one @mixin block and set the parameters to be passed in — which we use to select our breakpoints, like so:

Then to use our mixins in this manner, we’d select it like so: