What are Mixins in Sass, how do you define them and how do you use them?
Experience Level: Junior
Tags: Sass
Answer
Mixins work like programmable CSS templates. You define mixin once and then you can use it multiple times on multiple places with different parameters. Mixins will generate parametrized CSS.
The mixin is defined using keyword @mixin, you also provide mixin name, mixin parameters and mixin body.
The mixin can be used using keyword @include.
It looks like this:
Sass:
@mixin circle($radius, $bgColor) {
height: $radius*2;
width: $radius*2;
border-radius: $radius;
background-color: $bgColor;
}
.my-shape1 {
@include circle(20px, red)
}
The Sass from above will be compiled to the following CSS:
.my-shape1 {
height: 40px;
width: 40px;
border-radius: 20px;
background-color: red;
}
Note how the mixin definition was removed and is not present in the compiled CSS code at all. Also note that there is expression $radius*2
defined in Sass. Expressions are another feature of Sass.
Related Sass job interview questions
What does the @include keyword do in Sass?
Sass JuniorWhat is the advantage of using Sass mixins? When would you use them?
Sass JuniorWhat are variables in Sass, how do you use them and what is the advantage of using variables?
Sass JuniorTell me some ways how can you compile Sass to CSS
Sass JuniorWhat does it mean when someone says compile Sass to CSS?
Sass Junior