Part 4—CSS Preprocessing

25 SCSS mixin

Mixin lets us reuse common code in different places.

We can define styles like this:

@mixin bordered {
  border: 1px solid black;
}

Or we may provide argument:

@mixin bordered($color:black, $radius:0) {
  border: 1px solid $color;
  border-radius: $radius;
}

Then we can use our mixin in different places:

header {
  @include bordered(blue);

  width: 100%;
}
nav li {
  @include bordered(white, 5px);
}

Here is an example on how we can use the mixin to create a toggable debugging border.

 $show-debug: true;
@mixin debug ($color:red) {
  @if $show-debug {
    border: 1px solid $color;
  }
}

In the .col and nav li:

.col {
  padding: 0 10px;
  width: 100%;

  @include debug;

  @media screen and (min-width: $breakpoint) {
    float:left;
  }
}
nav li {
  width: 100%;
  padding: 5px;

  @include debug(green);
}

License

SCSS mixin Copyright © by makzan. All Rights Reserved.

Share This Book

Notice: 2nd edition update is work-in-progress. See update logs for details.