Let’s look at using @mixins in SCSS. You can look at mixins like the import we used before. But mixins place specific codes on the element we are mixing.
Defining our Mixin
We use the @mixin directive to define our mixin, so let’s go ahead and create our first one:
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
Note: Naming in SCSS can be either with - or _; they are considered the same and can be used simultaneously!
Using our Mixin
To use our mixin, we use the @include statement:
.container {
@include flex-center;
height: 100vh;
}
Our properties on the mixin will now also exist on the container element.
Mixin inside a Mixin
Another cool thing we can do is use mixins inside each other like so:
@mixin font {
font-family: Roboto, 'Helvetica Neue', Arial, sans-serif;
font-size: 2rem;
}
@mixin flex {
display: flex;
}
@mixin flex-center {
@include flex;
@include font;
justify-content: center;
align-items: center;
}
Mixin and Arguments
Something strong for using mixins is the use of arguments.
We can define our mixin as such:
@mixin button($background: blue, $padding: 10px, $color: #fff) {
background: $background;
padding: $padding;
display: block;
border-radius: 5px;
color: $color;
}
Note: We added default parameters, but these are not mandatory. You can leave them out.
And once we call it, pass these arguments:
.box {
@include button(#7afdd6, 20px, #ffffff);
}
Pro-tip
A good pro-tip is to use Mixins for vendor prefixes! It will save you so much time for border-radius, for example:
@mixin border-radius($amount) {
/* Safari 3-4, iOS 1-3.2, Android 1.6- */
-webkit-border-radius: $amount;
/* Firefox 1-3.6 */
-moz-border-radius: $amount;
/* Opera 10.5, IE 9, Safari 5, Chrome, Firefox 4, iOS 4, Android 2.1+ */
border-radius: $amount;
}
And we use this like so:
@include border-radius(20px);
Have a play around with these examples on Codepen.
See the Pen SCSS Mixins by Chris Bongers (@rebelchris) on CodePen.
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter