When you find yourself writing the same code over and over again, it feels like Sass mixins might help you out.
Sass mixins are CSS functions that you can include whenever you want.
Syntax
Remember how we wrote @keyframes
when creating CSS animations? The Sass mixin syntax is fairly similar:
The name of this mixin is overlay
. You can reference this mixin in any CSS rule by using @include
:
As usual, this .scss
will be compiled into .css
:
Reusability
The main purpose of a mixin is to make a set of properties reusable.
Like Sass variables (where you define your values on a single location), Sass mixins allow you to define properties on a single location.
The previous mixin can be reused in other rules:
Parameters
Because mixins are functions and because you might want to alter the output, mixins can accept parameters.
For example, this border-radius mixin prevents rewriting vendor prefixes and takes the actual radius value as a parameter:
The mixin circumvents the hassle of having to write all vendor prefixes, and uses the $radius
to allow defining the same radius value for every vendor property.
Optional parameters
If you want a parameter to have a default value while providing the possibility to set one occasionally, you can create optional paramaters:
This mixin is the one used by this website to add labels in the top left corner of code snippets. It has 3 optional parameters, each of them with their own default value set with a colon :
.
This mixin is used several times throughout the code:
The div.highlighter-rouge
will use the mixin’s default values:
- text
"Code"
- background:
$yellow
- color:
rgba(black, 0.5)
The .css
and .scss
versions, because their parameters are set, will use different labels and colors.
Mixin libraries
If you don’t want to spend time writing your own Sass mixins, you can use any of the following mixin libraries:
- Bourbon: bourbon.io
- Compass: compass-style.org
- Susy: susy.oddbird.net