How to use Sass mixins to group CSS declarations, and generally reduce the amount of code you need to write.
In Sass, a mixin allows you to create groups of CSS declarations that you can reuse throughout your CSS. This helps reduce the amount of code you need to write, as you write it once, and then reference it where ever you need.
While this might sound a lot like using variables, a mixin takes it up a few notches. While a variable can store a value, a mixin can store a whole declaration. In fact, a mixin can store many declarations.
But another great thing about mixins is, they can also accept values to be passed in. So a mixin can be quite dynamic.
How to Create and Use a Mixin
To create a mixin you use the
@mixin directive and give it a name.
Once you've created the mixin, you can reference it as a CSS declaration with
@include followed by the name of the mixin.
A common use for mixins is vendor prefixes.
When browser vendors add new CSS features to their browsers, they often implement them with a browser prefix. They do this when they're implementing a feature that's not yet in the official CSS specification. This is vendor-specific and allows CSS coders to write specific code that they know will work on a particular browser.
-webkit-border-radius will work on Chrome and Safari browsers, while
-moz-border-radius is specific to Firefox. The CSS standard is simply
Let's create a mixin for this particular CSS property then.
This results in the following CSS being compiled:
Passing in a Value
You can make your mixin more flexible by passing in an argument. This argument is then stored in a variable that you can use within the mixin.
We can extend the above example to accept a value for the border radius. So instead of hard-coding the radius within the mixin, we can pass that in where ever we call the mixin.
The benefit of doing this is that we're not locking ourselves in to having only one border radius. We can now use the same mixin to set borders of any radius.
The compiled CSS will look like this:
Of course, this mixin can be referenced as many times as you need. That's where the real benefit comes in. If you have say, a dozen elements all requiring a border radius, you can add it without having to type out the vendor prefixes each time.
Plus, there comes a time when a particular vendor prefix is no longer required (i.e. when they support the CSS standard without the prefix). At that time, you can simply remove it from the mixin. No need to update it in multiple places.
However, vendor prefixes aren't the only reason to use mixins. You can use them for any set of declarations that you may need to repeat across your style sheets.