TExcelTAD
Home › Sass › Sass @while

Sass @while

@while repeats a block as long as a condition is true. It's the most flexible loop in Sass — and the one you'll need least. Reach for it when the number of steps depends on a calculated value rather than a fixed count or a list.

scss
@while <condition> {
  …   // something here must eventually make the condition false
}

A basic @while loop

scss · try it yourself
$i: 1;

@while $i <= 3 {
  .level-#{$i} {
    padding-left: $i * 12px;
  }
  $i: $i + 1;
}
.level-1 {
  padding-left: 12px;
}

.level-2 {
  padding-left: 24px;
}

.level-3 {
  padding-left: 36px;
}

The last line inside the loop updates $i. Without it, the condition would stay true forever and the compiler would hang.

Note: Unlike most languages, there's no $i++ in Sass. Write $i: $i + 1;.

A loop with an unknown number of steps

Here's a case @for can't express neatly: generate a modular type scale that grows by a ratio until it passes a maximum size.

scss · try it yourself
@use "sass:math";

$size: 12px;
$ratio: 1.25;
$step: 0;

@while $size < 40px {
  .text-step-#{$step} {
    font-size: math.round($size);
  }
  $size: $size * $ratio;
  $step: $step + 1;
}
.text-step-0 {
  font-size: 12px;
}

.text-step-1 {
  font-size: 15px;
}

.text-step-2 {
  font-size: 19px;
}

.text-step-3 {
  font-size: 23px;
}

.text-step-4 {
  font-size: 29px;
}

.text-step-5 {
  font-size: 37px;
}

The loop stopped by itself once the size reached 40px or more — we never had to calculate how many steps that would be.

@while inside a function

@while is common in @functions that search for a value. This function halves a number until it fits under a limit:

scss · try it yourself
@use "sass:math";

@function fit-under($value, $limit) {
  @while $value > $limit {
    $value: math.div($value, 2);
  }
  @return $value;
}

.thumb {
  width: fit-under(1000px, 150px);
  height: fit-under(600px, 150px);
}
.thumb {
  width: 125px;
  height: 150px;
}

Choosing the right loop

Loop Best for Example
@each Items in a list or map Colour variants, breakpoints
@for A known numeric range .col-1 … .col-12
@while Unknown number of steps, stop on a condition Type scale up to a max, searching

Any @for can be written as @while, but @for is shorter and can't loop forever. Prefer @each and @for; save @while for the rare cases that need it.

Tip: If your editor freezes while Sass compiles, check every @while for a missing update of the loop variable.

Test yourself

What happens if the variable in a @while condition is never updated?

  1. The loop runs once
  2. Sass skips it
  3. The compile never finishes (infinite loop)
  4. Sass increments it automatically

How do you increase $i by one in Sass?

  1. $i++;
  2. $i += 1;
  3. $i: $i + 1;
  4. @increment $i;

When is @while a better choice than @for?

  1. Looping over a map
  2. When the number of iterations depends on a computed condition
  3. Generating .col-1 to .col-12
  4. Never