Mixins are the Sass equivalent of macros in other programming languages. If you’ve programmed before you could think of them as functions, procedures, or methods, But they aren’t demeaning any of these concepts because their function is to generate code at compile time not execute code at run time.

Mixins can be thought of as macros in a programming language, but technically, SCSS mixins are used to generate code at the compiler, not execute it at run time.

An example:

a.button {
  background: black;
  color: white;
  padding: 10px 20px;
  @include border-radius(5px);
}
Copy the code

After compiling:

a.button {
  background: black;
  color: white;
  padding: 10px 20px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  -ms-border-radius: 5px;
  -o-border-radius: 5px;
  -khtml-border-radius: 5px;
  border-radius: 5px;
}
Copy the code

I used the @include directive to tell Sass that I wanted to call out to a mixin. Use the @include directive to tell Sass to call out mixin in the CSS. Pass parameters through parentheses.

Take a look at the border-radius implementation code:

@mixin border-radius($radius) {
  -moz-border-radius: $radius;
  -webkit-border-radius: $radius;
  -ms-border-radius: $radius;
  border-radius: $radius;
}
Copy the code

A mixin passes default arguments:

@mixin border-radius($radius: 5px) {... }Copy the code

Or define a global variable:

$default-border-radius: 5px! default;@mixin border-radius($radius: $default-border-radius) {
 ...
}
Copy the code

SCSS mixins also support conditional directives @if:

@mixin border-radius($radius: 5px, $moz: true, $webkit: true, $ms: true) {
  @if $moz    { -moz-border-radius:    $radius; }
  @if $webkit { -webkit-border-radius: $radius; }
  @if $ms     { -ms-border-radius:     $radius; }
  border-radius: $radius;
}
Copy the code

The above usage is called the keyword argument.

Thus, if we don’t consider IE support in the project, we can simply write:

@include border-radius($ms: false);
Copy the code

Instead of writing it like this:

@include border-radius(5px, true, true, true);
Copy the code

There is no need to pass parameters in order:

@include border-radius($ms: false, $radius: 10px);
Copy the code