0
0
SASSmarkup~5 mins

Grid column generator with loops in SASS

Choose your learning style9 modes available
Introduction

Loops help create many grid column styles quickly without writing each one by hand.

When you want to make a grid system with many column widths.
When you need consistent spacing and sizing for columns in a layout.
When you want to save time by automating repetitive CSS code.
When you want to easily update column numbers by changing one value.
When building responsive designs that use grid columns.
Syntax
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.

Examples
This creates classes .col-1 to .col-4 that span 1 to 4 columns.
SASS
@for $i from 1 through 4 {
  .col-#{$i} {
    grid-column: span $i;
  }
}
Using a variable $total-columns makes it easy to change how many columns you generate.
SASS
$total-columns: 6;
@for $i from 1 through $total-columns {
  .col-#{$i} {
    grid-column: span $i;
  }
}
Sample Program

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.

SASS
@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;
  }
}
OutputSuccess
Important Notes

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.

Summary

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.