0
0
SASSmarkup~5 mins

Generating utility classes with loops in SASS

Choose your learning style9 modes available
Introduction

Loops help you create many similar CSS classes quickly. This saves time and keeps your code neat.

When you want to make many spacing classes like margin or padding with different sizes.
When you need color classes for different shades of a color.
When you want to create size classes for fonts or widths in steps.
When you want to avoid writing repetitive CSS by hand.
Syntax
SASS
@for $i from <start> through <end> {
  .class-#{$i} {
    property: value * $i;
  }
}

The @for directive runs a loop from a start number to an end number.

Use #{$i} to insert the loop number into class names or values.

Examples
This creates margin classes .m-1, .m-2, and .m-3 with increasing margin sizes.
SASS
@for $i from 1 through 3 {
  .m-#{$i} {
    margin: 0.5rem * $i;
  }
}
This makes font size classes from .text-size-1 to .text-size-5 with growing font sizes.
SASS
@for $i from 1 through 5 {
  .text-size-#{$i} {
    font-size: 1rem + 0.2rem * $i;
  }
}
Sample Program

This code creates padding classes .p-1 to .p-4 with increasing padding sizes from 0.25rem to 1rem. It also creates background color classes .bg-light-1 to .bg-light-3 with increasing blue transparency.

Use these classes in HTML to see boxes with different padding and background shades.

SASS
@use 'sass:math';

@for $i from 1 through 4 {
  .p-#{$i} {
    padding: math.div(1 * $i, 4) * 1rem;
  }
}

@for $i from 1 through 3 {
  .bg-light-#{$i} {
    background-color: rgba(0, 0, 255, 0.2 * $i);
  }
}

/* HTML example to test classes */

/*
<div class="p-1 bg-light-1">Box 1</div>
<div class="p-2 bg-light-2">Box 2</div>
<div class="p-3 bg-light-3">Box 3</div>
<div class="p-4">Box 4</div>
*/
OutputSuccess
Important Notes

Loops in Sass help avoid writing repetitive CSS code.

Use @for for counting loops, @each for lists, and @while for conditions.

Remember to compile Sass to CSS before using it in the browser.

Summary

Loops let you create many CSS classes quickly and cleanly.

Use @for with #{$variable} to insert numbers in class names.

This saves time and keeps your styles consistent.