Loops help create many grid column styles quickly without writing each one by hand.
Grid column generator with loops in SASS
@for $i from 1 through $total-columns { .col-#{$i} { grid-column: span $i; } }
The @for loop runs from a start number to an end number.
Use #{$i} to insert the loop number into class names or values.
.col-1 to .col-4 that span 1 to 4 columns.@for $i from 1 through 4 { .col-#{$i} { grid-column: span $i; } }
$total-columns makes it easy to change how many columns you generate.$total-columns: 6; @for $i from 1 through $total-columns { .col-#{$i} { grid-column: span $i; } }
This code creates a grid container with 4 equal columns. It uses a loop to make classes .col-1 to .col-4. Each class spans that many columns. The background color changes for each column size to help see the difference.
@use 'sass:math'; $total-columns: 4; .container { display: grid; grid-template-columns: repeat(#{$total-columns}, 1fr); gap: 1rem; max-width: 600px; margin: 2rem auto; } @for $i from 1 through $total-columns { .col-#{$i} { grid-column: span $i; background-color: hsl(math.div(360, $total-columns) * $i, 70%, 80%); padding: 1rem; border: 1px solid hsl(math.div(360, $total-columns) * $i, 70%, 50%); text-align: center; font-weight: bold; border-radius: 0.5rem; } }
Use @use 'sass:math' for math functions like division to avoid warnings.
Loop variables can be used inside strings with #{$variable} to create dynamic class names.
Changing $total-columns updates the grid and all column classes automatically.
Loops in Sass help generate many grid column classes quickly and consistently.
Use @for with variables to make your grid flexible and easy to update.
Dynamic class names and properties make your CSS cleaner and easier to maintain.