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.


This loop is designed to generate classes (for example: .f—color-a) that apply text color using the options ($color-options) we’ve previously defined in the variables.

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

The loop will output CSS utility classes like .f—color-a, .f—color-b, etc.—based on the key names in the $color-options map.

These classes apply their respective color values and are available globally in the project.

📌 This loop will iterate over a map like this:
Section titled “📌 This loop will iterate over a map like this:”
$color-options: (
a: $color-a,
b: $color-b,
c: $color-c,
);

See how $color-options is defined in the Vars page →

<p class="f--color-a">This is a paragraph with color A</p>
  1. Using the variable directly
.c--component-a {
color: map-get($color-options, a);
}
  1. Extending the generated foundation class
.c--component-a {
@extend .f--color-a;
}