What is the advantage of using Sass mixins? When would you use them?

Experience Level: Junior
Tags: Sass

Answer

Mixins improve the code maintainability as they allow you to define a block of a code once and then use it multiple times, so that you don't need to duplicate it.

  • Use Mixins at places where you would be using same rule sets in multiple different selectors.
  • Use Mixins if you need to parametrize rule sets that are used in multiple different selectors.

Sass:

@mixin alert($color, $bgColor) {
  border: solid 1px $color;
  color: $color;
  background-color: $bgColor;
}

.alert-success {
  @include alert(green, whitesmoke)
}

.alert-error {
  @include alert(red, yellow)
}

The Sass from above will be compiled to the following CSS:

.alert-success {
  border: solid 1px green;
  color: green;
  background-color: whitesmoke;
}

.alert-error {
  border: solid 1px red;
  color: red;
  background-color: yellow;
}

Comments

No Comments Yet.
Be the first to tell us what you think.
Sass for beginners
Sass for beginners

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

Test yourself