Loops help you create many similar CSS classes quickly. This saves time and keeps your code neat.
Generating utility classes with loops in 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.
.m-1, .m-2, and .m-3 with increasing margin sizes.@for $i from 1 through 3 { .m-#{$i} { margin: 0.5rem * $i; } }
.text-size-1 to .text-size-5 with growing font sizes.@for $i from 1 through 5 { .text-size-#{$i} { font-size: 1rem + 0.2rem * $i; } }
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.
@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> */
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.
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.