Creating and Including Mixins

A mixin is a reusable block of Sass declarations or rules. Define one with @mixin and include it with @include.

Mixins are useful for repeated patterns such as focus indicators, layout helpers, responsive rules, and compatibility declarations. They can also emit nested selectors and media queries.

Unlike a function, a mixin primarily produces stylesheet output. A function computes and returns a value that can be used in an expression.

Because a mixin's declarations are generally expanded wherever it is included, including a large mixin in many selectors can duplicate CSS. Reuse should be evaluated against the size and clarity of the generated output.

Reusable Focus and Flexbox Mixins
@mixin flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

@mixin focus-ring($color: #333) {
  &:focus-visible {
    outline: 3px solid $color;
    outline-offset: 3px;
  }
}

.modal {
  @include flex-center;
}

.button {
  @include focus-ring(#5b5bd6);
}
💡 The flex-center mixin emits three declarations. The focus-ring mixin accepts a color argument and generates a nested focus selector. A mixin is a good abstraction when multiple components need the same meaningful behavior. It is less useful when it merely hides a single obvious declaration without improving consistency.
Knowledge Check

Which pair of directives defines and invokes a Sass mixin?