How to Use Loops in SCSS (for, each, while)

Using loops in SCSS allows you to generate repetitive styles efficiently without writing the same code multiple times. SCSS supports @for, @each, and @while loops, which help create dynamic classes for spacing, grids, or utility systems. The @for loop is useful for iterating a set number of times, while @each works with lists or maps, and @while runs based on a condition. These loops help automate styling tasks and keep your code clean and scalable. Overall, SCSS loops improve productivity and make your stylesheets more powerful and maintainable.

Why Use Loops in SCSS?

Loops help you generate repetitive styles automatically. Instead of writing the same CSS multiple times, you can use loops to create dynamic classes efficiently.

Example:

@for $i from 1 through 3 {
.m-#{$i} {
margin: #{$i * 10}px;
}
}

Using @for Loop

The @for loop runs a specific number of times. It is useful for creating utility classes like spacing, widths, etc.

Example:

@for $i from 1 through 5 {
.p-#{$i} {
padding: #{$i * 5}px;
}
}

Using @each Loop

The @each loop iterates over a list or map. It is perfect for working with colors, font sizes, or themes.

Example:

$colors: red, green, blue;

@each $color in $colors {
.text-#{$color} {
color: $color;
}
}

Using @while Loop

The @while loop runs until a condition becomes false. It is less commonly used but helpful for dynamic logic.

Example:

$i: 1;

@while $i <= 3 {
.w-#{$i} {
width: #{$i * 50}px;
}
$i: $i + 1;
}

Real-World Example (Dynamic Utility Classes)

Loops are widely used to create reusable utility classes like spacing, grids, and responsive helpers.

Example:

$sizes: 10, 20, 30;

@each $size in $sizes {
.gap-#{$size} {
gap: #{$size}px;
}
}