Design Tools - SCSS Mixin Basics

SCSS, also known as Sass, is a css preprocessor that provides several powerful features made to streamline working with CSS.

One of my favorite tools that SCSS provides is the mixin, which I think of as a function that outputs css. Coupled with Scss variables, mixins are an effective method of changing and maintaining designs on projects.

Here's a quick example of how you could use mixins. I will be creating a mixin that will output a media query for

First, lets create a mixin:

@mixin breakpoint($size) {
    @if $breakpoint == "tablet" {
        @media (min-width: 500px) {
            @content;
        }
    }
    @else if $breakpoint == "monitors" {
        @media (min-width: 800px) {
            @content;
        }
    }
    @else if $breakpoint == "widescreen" {
        @media (min-width: 1280px) {
            @content;
        }
    }
}

So what's happening here? Well, the @mixin creates the mixin, naming it breakpoint. Our breakpoint mixin will take a variable $size as it's input, and spit out a media query of the appropriate size. To use the mixin, you just need to @include it in your scss like so:

.exampleDiv {
    width: 80%;
    @include breakpoint(widescreen) {
        width: 100%;
    }
}

Which will give you the following in your compiled css:

 .exampleDiv{
     width: 80%;
     @media (min-width: 1280px) {
        width: 100%;
    }
 }

Now you might be wondering, how does this help me Mino you fool? The scss and css are almost identical, the mixin didn't shorten my code at all!

Well, that is true. And in most cases the use of the mixin won't make your scss shorter. BUT THAT'S NOT THE POINT. The power of the mixin in this example is that it provides a variable output, while consolidating site-wide declarations in one place.

Lets say you have just finished a project, and your client decides that they want to enlarge the mobile version of the site so that tablet users get the same UI. Well, isntead of having to go through and change EVERY breakpoint in your code to reflect that, you only have to change the corresponding variable in your mixin.

So taking the example from above, this:

@if $breakpoint == "tablet" {
    @media (min-width: 500px) {
        @content;
     }
}

Becomes this:

    @if $breakpoint == "tablet" {
        @media (min-width: 800px) {
            @content;
        }
    }

And voila! You're done! Just compile your sass and everything is handled for you, no headaches worrying about whether you missed a media query or not.

Mixins can also be applied to many other aspects of your site design, such as setting colors and fonts for your theme, while giving you the power to quickly change them in one location. Awesome.

So what are you waiting for... start mixin!