SCSS Mixins

Code Reuse

Scott Price
2 min readOct 8, 2018

I recently had a phone interview and was asked some questions that I could have answered better. The purpose of this series of blog posts is to help me remember these concepts, so next time I will have a better answer. If others find these posts useful, all the better.

In SCSS, a mixin is a block of SCSS code that can be reused throughout your web site. This is one way to keep your code DRY. You can declare a mixin in SCSS like this:

@mixin buttons {
border: none;
color: black;
background-color: inherit;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
display: inline-block;
}

Use this mixin in your SCSS like this:

.myButton {
@include buttons;
}

However, this does not display the real power of mixins. You could accomplish the same thing in SCSS using @extend. Like a JavaScript function, SCSS mixins can accept parameters like this:

@mixin buttons($color) {
border: none;
color: $color;
background-color: inherit;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
display: inline-block;
}

An Example: Bootstrap-Like Buttons

Consider the following HTML:

<button class=”success”>Success</button>
<button class=”info”>Info</button>
<button class=”warning”>Warning</button>
<button class=”danger”>Danger</button>
<button class=”default”>Default</button>

Notice we are using classes similar to how they are used in Bootstrap. We could style these buttons similar to how they might be styled with Bootstrap using the following mixin:

@mixin buttons($color, $hoverBackgroundColor) {
border: none;
color: $color;
background-color: inherit;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
display: inline-block;
&:hover {
color: white;
background-color: $hoverBackgroundColor;
}
}

We would use the button mixin in our SCSS like this:

.success {
@include buttons(green, #4CAF50);
}
.info {
@include buttons(dodgerblue, #2196F3);
}
.warning {
@include buttons(orange, #ff9800);
}
.danger {
@include buttons(red, #f44336);
}
.default {
@include buttons(black, #999999);
}

The result looks like this:

Other Stories in this Series:

--

--

Scott Price

Front End Developer with Information Security Experience. See my resume and portfolio at www.scottaprice.com