SASS provides two kinds of loop directives.

  • While Loop
  • for loop

@while loop directive

@while loop allows running multiple code statements until the condition is false.

while(condition) {
   // CSS code statement
}

condition is a valid expression evaluated to be true or false.

if the condition is true, the code statement is executed. else does not execute code

Here is an Scss or sass @while loop code

$base: 30;
@while $base > 0 {
   .margin-#{$base} { margin-left: 1px * $base; }
  $base:$base - 5;
}

Generated Output:

.margin-30 {
     margin-left: 30px;
}
 .margin-25 {
     margin-left: 25px;
}
 .margin-20 {
     margin-left: 20px;
}
 .margin-15 {
     margin-left: 15px;
}
 .margin-10 {
     margin-left: 10px;
}
 .margin-5 {
     margin-left: 5px;
}

@for directive sass

@for directive used to execute a set of code statements with limited times based on the expression.

It provides two variations of for loop

  • for through loop Syntax
 @for  variable  from start through end {
    // CSS code statements
 }

It executes the code from start to end times by including the end value.

SCSS code

@for $base from 1 through 5 {
 .base-#{$base} { height: 5px * $base; }
}

Generated CSS

.base-1 {
     height: 5px;
}
 .base-2 {
     height: 10px;
}
 .base-3 {
     height: 15px;
}
 .base-4 {
     height: 20px;
}
 .base-5 {
     height: 25px;
}
  • for to loop for to loop executes from start to end by excluding the end value.
@for variable from start to end {
 // CSS code statements
}

Here is an @for to loop example

@for $base from 1 to 5 {
 .base-#{$base} { height: 5px * $base; }
}

for loop executes from 1 to 4 by excluding end value 5.

Generated CSS

.base-1 {
     height: 5px;
}
 .base-2 {
     height: 10px;
}
 .base-3 {
     height: 15px;
}
 .base-4 {
     height: 20px;
}

@for loop notes

  • start and end are numbers, and can also be functions that return integer values.
  • if the start greater than the end value, It decrements the value for each iteration

@each loop

@each loop directive used to iterate elements in the map or list.

Syntax

@each variable in Map or list{
     //CSS code
}


```css
$bases: "primary", "secondary", "neutral";
$radius:50;
@each $base in $bases {
 .#{$base}-radius {
 border-radius: $radius - 10;

 }
 $radius:$radius - 10;
}

Generated Output

 .primary-radius {
  border-radius: 40;
}
 .secondary-radius {
  border-radius: 30;
}
 .neutral-radius {
  border-radius: 20;
}