Adding Parameters to Your SASS Mixins

One of my favorite time-saving techniques in Sass is to add parameters to my mixins. It saves time by allowing you to write less code, especially when you're playing around in the prototyping phase.

Here is a simple example where we want to stay DRY and not repeat ourselves when creating different sized boxes in a flexbox layout. We add a $flexunit parameter with no default value which will let us define that value when we call (@include) the mixin like so:

@mixin flex($flexunit) {
 display: flex;
 flex: $flexunit;
}

.flex1 {
 @include flex(1);
}

.flex2 {
 @include flex(2);
}

.flex3 {
 @include flex(3);
}

The CSS this compiles to is:

.flex1 {
  display: flex;
  flex: 1;
}

.flex2 {
  display: flex;
  flex: 2;
}

.flex3 {
  display: flex;
  flex: 3;
}