Sass Basics: The Mixin Directive

Originally published at: http://www.sitepoint.com/sass-basics-the-mixin-directive/

For me finding Sass was a revelation. For the longest time I had tired of writing plain or ‘vanilla’ CSS. For a small site it was fine, but for larger sites the CSS quickly got out of hand. Debugging was a nightmare and I couldn’t help but feel like I could do more with my CSS.

I found Sass and everything changed. With Sass I could break my CSS down into modular chunks to make troubleshooting a breeze. I could also use programming concepts, such as functions and variables, when creating my CSS. And most importantly Sass introduced me to Mixins.

What is a mixin

A mixin allows us to create reusable chunks of CSS. Being able to do this helps us to avoid writing repetitive code. For example:

a:link {color: white;}
a:visited {color: blue;}
a:hover {color: green;}
a:active {color: red;}

Writing this code over and over again can get old very quickly, especially of you have a large site with a lot of links. With a mixin creating link can be done with Sass like this.

@mixin linx ($link,$visit,$hover,$active) {
    a {
        color: $link;
        &:visited {
            color: $visit;
        }
        &:hover {
            color: $hover;
        }
        &:active {
            color: $active;
        }
    }
}

How to include a mixin

To make use of a mixin you have to include it in your Sass files. To call the link mixin from above we would add this line.

Continue reading this article on SitePoint
2 Likes

Thank you Reggie for this article ! It’s a good explanation of the strengths of Sass Mixins.

Unfortunately your Padding-Mixin isn’t correct. You can’t separate the values with a comma in the output.

Good catch FrontendGuru. The mixin works, its my usage that is the problem. I was supposed to call the mixin like this:

@include pad(10px 20px 30px 20px);

Sass takes a list of values separated by commas or spaces, and in this example I was supposed to use spaces so that compilation doesn’t use commas.

Was correct initially but I changed while editing, what I get for working late at night. Thanks for the feedback, I will submit a correction.

Thanks for catching this, I’ve just updated the article so that the examples are now correct. I’m really pleased you liked it.

1 Like

Loved it. Thank you so much for the article. I helped me a lot.