Skip to content

Mixins

SCSS mixins are reusable blocks of CSS logic. You can think of them as functions for styles: they accept parameters and generate CSS dynamically.

They help reduce duplication and keep styles modular when the same rules need to be reused with slight variations.


Mixins are defined using the @mixin directive, followed by a name and optional parameters.

  • All mixins must start with make-
  • Mixins live inside the framework mixins folder

The following mixin defines a reusable typography configuration. It accepts an optional $weight parameter and sets responsive font sizes.

// Mixin file src/scss/framework/_mixins/foundation/font/_font.scss
@mixin make-font-a($weight: 400) {
font-family: $type-b;
font-weight: $weight;
line-height: 1.1;
font-size: 4.875rem;
-webkit-font-smoothing: antialiased;
@media all and ($viewport-type: $tablets) {
font-size: 3rem;
}
}

In Terra, mixins are not meant to be used directly in components by default. Instead, we use them to generate foundation classes, which are then reused via @extend.

This foundation class includes the mixin and compiles all its styles into a single reusable class.

src/scss/framework/foundation/font/_font.scss
.f--font-a {
@include make-font-a();
}

When SCSS compiles, the mixin’s styles are injected into .f—font-a.

02. Reuse the foundation class (preferred)

Section titled “02. Reuse the foundation class (preferred)”

Components should extend the foundation class, not re-include the mixin.

.c--component-a {
@extend .f--font-a;
}

This approach:

  • avoids duplicated CSS
  • keeps output smaller
  • centralizes style logic

Including a mixin directly inside a component should be the exception, not the rule.

Use @include only when:

  • the style variation cannot be represented by an existing foundation class
  • parameters need to be customized in a very specific case
.c--component-a {
@include make-font-a(600);
}

Foundation classes can also be applied directly in HTML when appropriate.

<p class="f--font-a">
This is a paragraph using the font A foundation style
</p>

  • Mixins define reusable style logic
  • In Terra, mixins are mainly used to generate foundation classes
  • Preferred workflow:
    1. Define a mixin
    2. Use it once in a foundation class
    3. Reuse it everywhere via @extend
  • Direct @include usage should be rare and justified

Knowledge Check

Test your understanding of this section

Loading questions...