iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

@for

@for is the SCSS counting loop: iterate a numeric range and generate rules. Use it for grid columns, opacity scales, animation keyframes, and any time you need N similar rules. Combine with @while when the iteration logic is conditional, but @for covers most cases.

@for patterns: grid, scales, keyframes

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

// 2) Opacity scale .o-1 .. .o-10
@for $i from 1 through 10 {
  .o-\#{$i} { opacity: math.div($i, 10); }
}

// 3) Spacing scale from a base
@use 'sass:math';
$base: 4px;
@for $i from 0 through 8 {
  .p-\#{$i} { padding: $i * $base; }
  .m-\#{$i} { margin:  $i * $base; }
}

// 4) Z-index scale
@for $i from 1 through 10 {
  .z-\#{$i} { z-index: $i * 10; }
}

// 5) Stagger animation delays
@for $i from 1 through 5 {
  .stagger:nth-child(\#{$i}) {
    animation-delay: $i * 80ms;
  }
}

// 6) @for from x through y vs from x to y
// 'through' is INCLUSIVE of y: 1 through 5 = 1,2,3,4,5
// 'to'      is EXCLUSIVE of y: 1 to 5      = 1,2,3,4
// 'through' is what you want 90% of the time.

// 7) Step with math
@for $i from 0 through 10 {
  $pct: $i * 10;
  .w-\#{$pct} { width: $pct + 0%; }
}

// 8) Nested @for for a matrix (rare but possible)
@for $row from 1 through 3 {
  @for $col from 1 through 4 {
    .cell-\#{$row}-\#{$col} {
      grid-row: $row;
      grid-column: $col;
    }
  }
}

// 9) Combine with @if to skip values
@for $i from 1 through 12 {
  @if $i % 2 == 0 {
    .even-col-\#{$i} { display: block; }
  }
}

// 10) Use a map + @each when keys are meaningful
//     Use @for when the index is purely numeric.
@each $name, $value in ('xs': 480px, 'sm': 768px, 'md': 1024px) {
  .\#{$name} { max-width: $value; }
}

// 11) Pitfalls
// - Hard-coding 12 in many places -> declare as a variable
// - Generating thousands of rules unnecessarily -> bundle size bloats
// - Forgetting math.div in modern Sass (use math.div instead of /)
// - Interpolation outside selectors: use #{} consistently

Why it matters

Use @for for purely numeric ranges (grid columns, opacity scales, animation delays) and @each with a map when the values are meaningful named tokens. The split keeps generated CSS readable and the SCSS source easy to extend without breaking the cascade.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
@for $i from 1 through 12 {
    .col-\#{$i} { width: percentage($i / 12); }
}
Try it Yourself »

Discussion

Loading…