Sass @for
@for counts from one number to another and runs a block for each value. Use it when you need numbered output: spacing scales, grid columns, :nth-child delays or z-index layers.
scss
@for $i from <start> through <end> { … } // includes end
@for $i from <start> to <end> { … } // stops BEFORE endthrough vs to
scss · try it yourself
@for $i from 1 through 3 {
.through-#{$i} { order: $i; }
}
@for $i from 1 to 3 {
.to-#{$i} { order: $i; }
}.through-1 {
order: 1;
}
.through-2 {
order: 2;
}
.through-3 {
order: 3;
}
.to-1 {
order: 1;
}
.to-2 {
order: 2;
}
through produced three rules (1, 2, 3), but to stopped before 3 and produced only two.
| Form | Values of $i for start 1, end 4 |
|---|---|
from 1 through 4 |
1, 2, 3, 4 |
from 1 to 4 |
1, 2, 3 |
from 4 through 1 |
4, 3, 2, 1 (counts down) |
A spacing scale
Multiply the counter by a base unit to build a utility scale:
scss · try it yourself
$unit: 4px;
@for $i from 0 through 4 {
.mt-#{$i} {
margin-top: $i * $unit;
}
}.mt-0 {
margin-top: 0px;
}
.mt-1 {
margin-top: 4px;
}
.mt-2 {
margin-top: 8px;
}
.mt-3 {
margin-top: 12px;
}
.mt-4 {
margin-top: 16px;
}
A simple grid
@for and math.div make column widths easy:
scss · try it yourself
@use "sass:math";
$columns: 4;
.row { display: flex; gap: 8px; }
@for $i from 1 through $columns {
.col-#{$i} {
flex: 0 0 calc(#{math.percentage(math.div($i, $columns))} - 8px);
}
}.row {
display: flex;
gap: 8px;
}
.col-1 {
flex: 0 0 calc(25% - 8px);
}
.col-2 {
flex: 0 0 calc(50% - 8px);
}
.col-3 {
flex: 0 0 calc(75% - 8px);
}
.col-4 {
flex: 0 0 calc(100% - 8px);
}
Staggered animations with :nth-child
scss · try it yourself
.list-item {
animation: fade-in 300ms both;
@for $i from 1 through 4 {
&:nth-child(#{$i}) {
animation-delay: $i * 80ms;
}
}
}.list-item {
animation: fade-in 300ms both;
}
.list-item:nth-child(1) {
animation-delay: 80ms;
}
.list-item:nth-child(2) {
animation-delay: 160ms;
}
.list-item:nth-child(3) {
animation-delay: 240ms;
}
.list-item:nth-child(4) {
animation-delay: 320ms;
}
Counting down
If the start is larger than the end, @for counts down:
scss
@for $level from 3 through 1 {
.layer-#{$level} { z-index: $level * 10; }
}
// .layer-3 { z-index: 30 } .layer-2 { … } .layer-1 { … }Tip: If you are iterating over named things (colours, breakpoints), prefer
@eachover a map — the names make the output self-documenting. Use@forwhen the number itself is the point.
Test yourself
How many times does @for $i from 1 to 5 run?
- 5
- 4
- 6
- 1
Which keyword makes the range include the end value?
- to
- until
- through
- upto
What does @for $i from 3 through 1 do?
- Nothing
- Counts down 3, 2, 1
- Throws an error
- Counts 1, 2, 3