Skip to content

Sass: @for

How Sass @for loop generates CSS rules by iterating through numbers using from to through or to syntax for dynamic styling.

@for

The @for rule, written @for <variable> from <expression> to <expression> { ... } or @for <variable> from <expression> through <expression> { ... }, counts up or down from one number (the result of the first expression) to another (the result of the second) and evaluates a block for each number in between. Each number along the way is assigned to the given variable name. If to is used, the final number is excluded; if through is used, it's included.

The .scss file:

$base-color: #036;

@for $i from 1 through 3 {
  ul:nth-child(3n + #{$i}) {
    background-color: lighten($base-color, $i * 5%);
  }
}

and the .css file:

ul:nth-child(3n + 1) {
  background-color: #004080;
}

ul:nth-child(3n + 2) {
  background-color: #004d99;
}

ul:nth-child(3n + 3) {
  background-color: #0059b3;
}

through vs to

The difference between the two keywords is whether the final number is included:

Keyword Range Iterations for 1 → 3
through Start … end 1, 2, 3
to Start … end − 1 1, 2
@for $i from 1 through 3 { /* runs 3 times: 1, 2, 3 */ }
@for $i from 1 to 3     { /* runs 2 times: 1, 2       */ }

Counting down

If the start number is greater than the end number, the loop counts downward:

@for $i from 3 through 1 {
  .item-#{$i} { order: $i; }
}
.item-3 {
  order: 3;
}
.item-2 {
  order: 2;
}
.item-1 {
  order: 1;
}

Practical example: grid columns

A common use for @for is generating a set of column-width classes:

@use "sass:math";

$columns: 12;

@for $i from 1 through $columns {
  .col-#{$i} {
    width: math.percentage(math.div($i, $columns));
  }
}
.col-1 { width: 8.3333333333%; }
.col-2 { width: 16.6666666667%; }
.col-3 { width: 25%; }
.col-4 { width: 33.3333333333%; }
.col-5 { width: 41.6666666667%; }
.col-6 { width: 50%; }
.col-7 { width: 58.3333333333%; }
.col-8 { width: 66.6666666667%; }
.col-9 { width: 75%; }
.col-10 { width: 83.3333333333%; }
.col-11 { width: 91.6666666667%; }
.col-12 { width: 100%; }

Summary

  • @for iterates from a start number to an end number, assigning each value to a variable.
  • through includes the final number; to excludes it.
  • The loop counts down automatically when the start is greater than the end.
  • Use interpolation #{$i} to build selector names, property values, or nth-child expressions dynamically.
  • Prefer color.adjust() from sass:color over the deprecated lighten() / darken() functions.
Navigation