What Are Mixins?

Mixins are one of the most used features of Sass. They let you break CSS down into modular chunks that you can reuse anywhere in your stylesheets. Being able to do this helps us to avoid writing repetitive code.

  1. Define the mixin with the mixin directive.
  2. Include the mixin inside of the rules using the include directive.

For mixins to work, they need to be defined before they are included, usually at the top of the style sheet, or in a separate mixins file as you learn in the later video.

Basic Understanding

SCSS

$max-width: 1000px;

@mixin center {
  width: 90%;
  max-width: $max-width;
  margin-left: auto;
  margin-right: auto;
}
.main-content {
  display: flex;
  flex-wrap: wrap;
  @include center;
}

CSS

.main-content {
  display: flex;
  flex-wrap: wrap;
  width: 90%;
  max-width: 1000px;
  margin-left: auto;
  margin-right: auto;
}

Pass Content Blocks to Mixins

You can use one mixin for different rules, but provide different content for each rule, by passing blocks of styles to mixins using the @content directive. This makes your mixins incredibly flexible.

SCSS

$btn-background: #dc143c;

@mixin button {
  font-size: 1.25em;
  background-color: $btn-background;
  @content
}
a {
  @include button {
    color: #f0f8ff;
  };
}

CSS

a {
  font-size: 1.25em;
  background-color: #dc143c;
  color: #f0f8ff;
}