Generate Repeated Utilities with @for
The @for directive iterates across a numeric range. It is useful when the generated selectors follow a predictable numeric pattern, such as a limited spacing scale or grid span utilities.
Sass supports through and to range syntax. through includes the ending number, whereas to stops before it.
For example, @for $i from 1 through 4 executes four iterations, while @for $i from 1 to 4 executes three.
Choose the smallest useful range. Large generated utility systems can increase CSS output and make class naming conventions harder to manage.
Generate Column Span Utilities
@for $i from 1 through 4 {
.grid-span-#{$i} {
grid-column: span $i;
}
}💡 The loop generates four selectors:
.grid-span-1, .grid-span-2, .grid-span-3, and .grid-span-4.
The generated declarations use CSS Grid's grid-column property. Ensure that the generated span values are meaningful within the grid layouts used by your application.Knowledge Check
How many iterations occur in `@for $i from 1 through 4`?