Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Control Directives and Maps

Sass Loops: @each, @for and @while

Generate repetitive CSS with Sass loops: @for with from, through and to, @each over lists and maps with destructuring, @while, loop scope and when not to loop.

Some CSS is repetitive by nature: twelve grid column widths, a spacing scale, one utility class per brand color, a stack of z-index layers. Typing it by hand invites typos and makes changes painful. Sass has three loop directives that write the repetition for you, and the output is ordinary CSS. Together with interpolation they are the engine behind utility-class frameworks.

@for: counting

@for runs its block once for each number in a range. There are two forms:

  • @for $i from 1 through 3 includes both ends: 1, 2, 3.
  • @for $i from 1 to 3 excludes the end: 1, 2.
SCSS
@for $i from 1 through 4 {
  .mt-#{$i} { margin-top: $i * 0.25rem; }
}

Output: .mt-1 { margin-top: 0.25rem; }, .mt-2 { margin-top: 0.5rem; }, .mt-3 and .mt-4. The loop variable $i is a normal number you can use in math and interpolation.

The range can count down: @for $i from 3 through 1. The numbers must be integers and carry compatible units.

A grid built with @for

@each: walking a list

@each $item in $list runs once per element:

SCSS
$sizes: sm, md, lg;

@each $size in $sizes {
  .btn-#{$size} {
    @if $size == lg { font-size: 1.25rem; } @else { font-size: 1rem; }
  }
}

Loops and conditions combine naturally: the loop makes the rules and the @if picks the details.

A list can hold lists, and @each can destructure each inner list into several variables:

SCSS
$icons: (home "๐Ÿ ") (search "๐Ÿ”Ž") (user "๐Ÿ‘ค");

@each $name, $glyph in $icons {
  .icon-#{$name}::before { content: $glyph; }
}

@each over a map

A map yields a key and a value per iteration. This is the standard way to generate utilities from design tokens:

SCSS
$colors: (
  "primary": #0ea5e9,
  "danger":  #dc2626,
  "success": #16a34a
);

@each $name, $value in $colors {
  .text-#{$name} { color: $value; }
  .bg-#{$name}   { background: $value; }
}

Change or extend the map and all the classes follow. Maps get a lesson of their own next: Maps.

Generate classes from a map

@while: loop on a condition

@while repeats as long as its condition is true. Make sure something inside changes the condition, or compilation never ends.

SCSS
$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}

The output has .item-6, .item-4 and .item-2. This example needs a step of 2, which is awkward with @for; otherwise prefer @for or @each, which cannot loop forever.

Loop variables and scope

Variables created inside a loop exist only in that iteration. But, as covered in Variables, assigning to a variable that already exists outside the loop updates it, which lets you accumulate:

SCSS
$total: 0;
@each $n in 1, 2, 3 { $total: $total + $n; }
.sum { value: $total; }   // 6

Idioms you will use again and again

Responsive variants (loop over a breakpoints map, as in Maps):

SCSS
@each $bp, $min in (sm: 640px, md: 768px, lg: 1024px) {
  @media (min-width: $min) {
    .#{$bp}\:hidden { display: none; }
  }
}

The backslash escapes the colon so the class name .sm:hidden is valid CSS.

Z-index layers from a list, so no one has to remember magic numbers:

SCSS
$layers: base, dropdown, sticky, modal, toast;
@each $layer in $layers {
  .z-#{$layer} { z-index: index($layers, $layer) * 100; }
}

(index is list.index from the list module; the global index() still works but prefer the module form.)

@for, @each and @while side by side

When not to loop

Loops can generate hundreds of classes in a few lines, and that is also the danger: CSS size grows quietly. Ask whether the page uses those classes. Prefer a small, intentional set (for example five spacing steps, not fifty), and consider a utility framework such as Tailwind CSS if you need a huge generated set with pruning. Looping is the right tool for fixed, design-token-sized sets.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many iterations does @for $i from 1 through 4 run?

    through includes the end value, so it runs for 1, 2, 3 and 4.
  2. 2. And @for $i from 1 to 4?

    to excludes the end value, so it runs for 1, 2 and 3.
  3. 3. What does @each $name, $value in $map give you?

    Destructuring a map in @each assigns the key to the first variable and the value to the second.
  4. 4. What is the main risk of @while?

    Nothing stops a @while loop but its condition, so the body must change something that the condition tests.

Summary

  • @for counts (through includes the end, to excludes it); @each walks lists and maps; @while loops on a condition.
  • @each can destructure lists of lists and maps ($key, $value).
  • Combine loops with #{} interpolation to generate class names and property names.
  • Variables assigned inside loops update existing outer variables; new ones stay local.
  • Generate only the CSS you need; unused generated classes are dead weight.

Next: Maps