How to use the for loop in SASS

In your SASSSyntactically Awesome Style Sheets code, you might want to minimize your code and dynamically set values for some CSSCascade Style Sheets selectors. In this case, the SASS @for loop is the right choice.

Syntax


@for [loop variable] from [loop start] through [loop end]{
 /* CSS RULE */
}

See the example below:


@for $i from 1 through 5{
 /* CSS RULE */
}

Use case

You might need to style a certain class with distinction in size, color, or property. Consider the following example.


.style{
   font-size: 16px;
   &-1{
    color:red
   }
   &-2{
    color:green
   }
   ...
}

From the code above, we can use the @for loop of SASS to create this style nested inside the .style class. We can therefore have as many styles as we want, like .style-1, .style-2, .style-3, and so on.

Code

In the following example, we will create a card of different sizes card-size-1, card-size-2, card-size-3, card-size-4, and card-size-5.

We won’t have to write different CSS rules for each, because that would waste our time. Since the only difference we want is their sizes, the @for loop is ideal.

@for $i from 1 through 5{
.card-size-#{$i}{
width: 20px * $i;
height: auto;
}
}

The SASS code above will apply to the following HTML elements with the different card-size-* classes.

<div class="card-size-1">card 1</p>
<div class="card-size-2">card 2</div>
<div class="card-size-3">card 3</div>
<div class="card-size-4">card 4</div>
<div class="card-size-5">card 5</div>

When the elements above are viewed on a web page, they appear in different sizes. That is the power of the SASS @for loop.

Free Resources