# For, while, and each loops in Sass

Use Sass's `@for`, `@while`, and `@each` rules to generate repeated styles.

Sass has three looping rules. Their syntax is compact and close to plain
English.

## For loop

An [`@for` loop](https://sass-lang.com/documentation/at-rules/control/for/)
counts between two numbers:

```scss
@for $i from <start> through <end> {
  // Repeated styles
}
```

`through` includes the end value. Use `to` instead to exclude it.

This example creates four columns with decreasing widths:

```scss
@use 'sass:math';

@for $i from 1 through 4 {
  .col-#{$i} {
    width: math.div(100%, $i);
  }
}
```

It emits:

```css
.col-1 {
  width: 100%;
}
.col-2 {
  width: 50%;
}
.col-3 {
  width: 33.3333333333%;
}
.col-4 {
  width: 25%;
}
```

`$i` holds the current number. The `#{$i}` syntax interpolates that number into
the selector. Use `math.div()` for division because `/` is deprecated as a Sass
division operator.

## While loop

An [`@while` loop](https://sass-lang.com/documentation/at-rules/control/while/)
runs while its condition is true:

```scss
$count: 4;

@while $count > 0 {
  .delay-#{$count} {
    animation-delay: $count * 100ms;
  }

  $count: $count - 1;
}
```

Make sure the condition can become false. Prefer `@for` or `@each` when either
fits; they make the stopping point clearer.

## Each loop

An [`@each` loop](https://sass-lang.com/documentation/at-rules/control/each/)
runs once for every item in a list:

```scss
$authors: arnold, sylvester, dolph, jean-claude, chuck;

@each $author in $authors {
  .photo-#{$author} {
    background-image: url('/avatars/#{$author}.png');
  }
}
```

It can also unpack each key and value in a map. For more examples of Sass maps
outside a loop, see
[the Sass maps guide](/sass-maps-syntax-examples-and-good-things):

```scss
$breakpoints: (
  'small': 30rem,
  'medium': 48rem,
  'large': 64rem,
);

@each $name, $width in $breakpoints {
  .container-#{$name} {
    max-width: $width;
  }
}
```
