BudiBadu Logo
Samplebadu

SCSS by Example: Loops

Sass 3.x+

Generating repetitive CSS programmatically with this sample code demonstrating @for loop with through and to keywords, @each loop for list iteration, @each with maps for key-value pairs, and interpolation syntax for dynamic selectors.

Code

// @for loop
// through includes the end number (1 to 3)
@for $i from 1 through 3 {
  .col-#{$i} {
    width: 100% / 3 * $i;
  }
}

// @each loop (iterating over a list)
$icons: facebook, twitter, instagram;

@each $icon in $icons {
  .icon-#{$icon} {
    background-image: url('/images/#{$icon}.png');
  }
}

// @each with maps
$colors: (
  primary: blue,
  success: green,
  danger: red
);

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

Explanation

SCSS provides three loop directives for generating repetitive CSS rules. The @for directive iterates a specific number of times using either from ... through (inclusive of end value) or from ... to (exclusive of end value) syntax. The loop counter variable is available within the block and commonly used with interpolation #{$variable} to create dynamic selector names or property values.

The @each directive iterates over lists or maps. When iterating over a list, it assigns each item to a variable. When iterating over a map, it can destructure key-value pairs into separate variables using @each $key, $value in $map syntax. Interpolation is essential in loops for inserting variable values into selectors, property names, or values where plain variables would not be valid.

The @while directive executes a block as long as a condition remains true, providing flexibility for complex iteration logic. All loop directives execute at compile time, generating the full set of CSS rules in the output. This makes loops powerful for creating utility class systems, grid frameworks, or any pattern where similar rules need to be generated with systematic variations. The generated selectors and rules are fully expanded in the final CSS, so loops with many iterations can significantly increase file size.

Code Breakdown

3
@for $i from 1 through 3 iterates with i=1, i=2, i=3 inclusive.
4
.col-#{$i} uses interpolation to create .col-1, .col-2, .col-3 selectors.
12
@each $icon in $icons iterates over list items assigning each to $icon.
24
@each $name, $color in $colors destructures map into key-value pairs.