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.
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
As usual, this
.scss will be compiled into
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:
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.
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:
div.highlighter-rouge will use the mixin’s default values:
.scss versions, because their parameters are set, will use different labels and colors.
If you don’t want to spend time writing your own Sass mixins, you can use any of the following mixin libraries: