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.
How we define mixins
Section titled “How we define mixins”Mixins are defined using the @mixin directive, followed by a name and optional parameters.
Naming convention
Section titled “Naming convention”- All mixins must start with make-
- Mixins live inside the framework mixins folder
Example: defining a typography mixin
Section titled “Example: defining a typography mixin”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; }}How mixins are used in Terra
Section titled “How mixins are used in Terra”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.
01. Generate a foundation class
Section titled “01. Generate a foundation class”This foundation class includes the mixin and compiles all its styles into a single reusable class.
.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
When to include a mixin directly
Section titled “When to include a mixin directly”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);}Using foundation classes in HTML
Section titled “Using foundation classes in HTML”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>Summary
Section titled “Summary”- Mixins define reusable style logic
- In Terra, mixins are mainly used to generate foundation classes
- Preferred workflow:
- Define a mixin
- Use it once in a foundation class
- Reuse it everywhere via
@extend
- Direct
@includeusage should be rare and justified
Knowledge Check
Test your understanding of this section
Loading questions...