0
0
SASSmarkup~5 mins

@for loop (through vs to) in SASS

Choose your learning style9 modes available
Introduction

The @for loop in Sass helps you repeat styles easily. Using through or to changes how many times the loop runs.

When you want to create multiple similar CSS classes quickly.
When you need to apply styles to a series of numbered elements.
When you want to generate a range of styles with small differences.
When you want to control if the loop includes the last number or stops before it.
Syntax
SASS
@for $var from <start> through <end> {
  // styles
}

@for $var from <start> to <end> {
  // styles
}

through includes the end number in the loop.

to stops before the end number, so it excludes it.

Examples
This creates classes .item-1, .item-2, and .item-3.
SASS
@for $i from 1 through 3 {
  .item-#{$i} {
    width: 10px * $i;
  }
}
This creates classes .box-1, .box-2, and .box-3. It stops before 4.
SASS
@for $i from 1 to 4 {
  .box-#{$i} {
    height: 5px * $i;
  }
}
Sample Program

This Sass code creates circles with sizes doubling from 2ยน to 2ยณ rem and squares with sizes from 1.5rem to 4.5rem but stops before 4, so squares 1 to 3.

SASS
@use "sass:math";

@for $i from 1 through 3 {
  .circle-#{$i} {
    width: math.pow(2, $i) * 1rem;
    height: math.pow(2, $i) * 1rem;
    background-color: hsl(200, 70%, 50%);
    border-radius: 50%;
    margin: 0.5rem;
    display: inline-block;
  }
}

@for $j from 1 to 4 {
  .square-#{$j} {
    width: $j * 1.5rem;
    height: $j * 1.5rem;
    background-color: hsl(340, 70%, 50%);
    margin: 0.5rem;
    display: inline-block;
  }
}
OutputSuccess
Important Notes

Remember: through includes the last number, to excludes it.

You can use #{$var} to insert the loop number into class names or property values.

Loops help avoid writing repetitive CSS and keep your code clean.

Summary

@for loops repeat styles for a range of numbers.

through includes the last number in the loop.

to stops before the last number, excluding it.