Skip to content

SCSS Loops

SCSS loops allow us to automate repetitive CSS tasks, especially when working with predefined maps of variables like colors. They are extremely useful for generating utility or foundation classes consistently and efficiently.

Instead of writing dozens of repetitive style declarations by hand, we use @each, @for, or @while loops to dynamically generate CSS classes based on variables—keeping our code DRY and scalable.


Let’s walk through a real example: generating color utility classes from a variable map. This is one of the most common uses of loops in Terra’s SCSS framework.

First, we define our colors in a map structure in _vars.scss. This is what we’ll loop through:

src/scss/framework/_vars/_vars.scss
$color-a: #7B44D1;
$color-b: #4D49F3;
$color-c: #26DAF6;
$color-options: (
a: $color-a,
b: $color-b,
c: $color-c,
);

Now we iterate over that map to generate our utility classes:

src/scss/framework/foundation/color/_color.scss
@each $color-name, $color in $color-options {
.f--color-#{$color-name} {
color: $color;
}
}

Breaking it down:

  • @each — starts the loop
  • $color-name — the key from the map (e.g., a, b, c)
  • $color — the value from the map (e.g., #7B44D1, #4D49F3)
  • $color-options — the map we’re iterating over
  • #{$color-name} — interpolation that inserts the key into the class name

When the SCSS compiles, the loop generates CSS like this:

.f--color-a {
color: #7B44D1;
}
.f--color-b {
color: #4D49F3;
}
.f--color-c {
color: #26DAF6;
}

These classes are now available globally throughout the project.


Once the loop has generated our utility classes, we can use them in two ways:

  • In HTML: Apply the class directly to any element:
<p class="f--color-a">This text uses color A</p>
<h2 class="f--color-b">This heading uses color B</h2>
  • In SCSS: Reference them in your component styles with @extend:
.c--component-a {
@extend .f--color-a;
}

Knowledge Check

Test your understanding of this section

Loading questions...