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
Sass for beginners
Sass for beginners

Are you learning Sass? Try our test we designed to help you progress faster.

Test yourself