@for and @while

Generate numbered rules with counting loops.

Syntax@for $i from 1 through 12 { } @while $cond { }

@for counts through a numeric range, perfect for generating numbered utilities like grid columns or spacing steps.

through vs to

  • @for $i from 1 through 5 — includes 5 (1,2,3,4,5).
  • @for $i from 1 to 5 — excludes 5 (1,2,3,4).

@while

@while repeats as long as a condition holds. It is rarely needed — @for and @each cover most cases — but useful for non-linear steps.

Example

Example · css
// 12-column width utilities
@use 'sass:math';

@for $i from 1 through 12 {
  .col-#{$i} {
    width: math.percentage(math.div($i, 12));
  }
}

/* .col-1 { width: 8.3333333333%; }
   .col-6 { width: 50%; }
   .col-12 { width: 100%; } */

When to use it

  • A developer uses @for to generate twelve column-width classes (.col-1 through .col-12) without manually writing each percentage.
  • A type scale generator uses @for to loop through power values and apply a ratio to a base size, producing h1-h6 font sizes mathematically.
  • A developer uses @while in an advanced scale computation to keep halving a value until it falls below a minimum threshold.

More examples

@for to generate column classes

Uses @for from 1 through 12 to generate all twelve column classes with computed grid-column and percentage width.

Example · css
@use 'sass:math';

@for $i from 1 through 12 {
  .col-#{$i} {
    grid-column: span $i;
    width: math.percentage(math.div($i, 12));
  }
}

@for with heading scale

Loops from h1 to h6 and applies an inverse power of the scale ratio so h1 is the largest and h6 is smallest.

Example · css
@use 'sass:math';

$base: 1rem;
$ratio: 1.25;

@for $i from 1 through 6 {
  h#{$i} {
    font-size: $base * math.pow($ratio, 7 - $i);
  }
}

@while for threshold computation

Uses @while to halve an icon size on each iteration, generating icon classes for 512px, 256px, 128px… down to 16px.

Example · css
@use 'sass:math';

$size: 512px;
$step: 0;

@while $size >= 16px {
  .icon-#{$size} { width: $size; height: $size; }
  $size: math.div($size, 2);
  $step: $step + 1;
}

Discussion

  • Be the first to comment on this lesson.