For, while, and each loops in Sass

Sass looping syntax guide.

I got news for you, loops is Sass are not that different from other languages. for loops are pretty much the same in all languages, see an interesting for loop timeline, the saga starts as early as 1957. In Sass, things are more like in Ruby than in, say, JavaScript, thus the loop syntax looks more plain English than unfathomable jargon.

For loop

The really straightforward syntax is:

@for $var from <start> through <end>

Let’s Imagine that we have to print styles for eight columns, with an ascending number in the end, and a different width for each column. Every columns has to be written down individually of course, boring and futile.

For loop shortens this ordeal significantly:

@for $i from 1 through 8 {
    $width: percentage(1 / $i)

    .col-#{$i} {
        width: $width;

It emits the following CSS:

.col-1 {width: 100%;}
.col-2 {width: 50%;}
.col-3 {width: 33.333%;}
.col-4 {width: 25%;}
.col-5 {width: 20%;}
.col-6 {width: 16.666%;}
.col-7 {width: 14.285%;}
.col-8 {width: 12.5%;}

Let’s break that down:

  • @for $i from 1 through 8 – Start from number 1 and run the loop 8 times.
  • $width: percentage(1 / $i)$i is the increment variable, it can be called anything, though.
  • .col-#{$i} – The columns number, note that the $i is interpolated, whenever you have another character ‘touching’ the variable, or it’s between quotes, it needs to be interpolated.

While loop

While loop runs while a condition is met.

$num: 4;

@while $num > 0 {
    .module-#{$num} {
        content: "#{$num}";

    $num: $num - 1;

Each loop

Ruby has an each loop also, PHP has foreach. There, the loop takes a list and works with that, lists in Sass are basically arrays. Here we have a list of names, and then we iterate that list as long as it lasts:

$list: arnold sylvester dolf jean chuck

@mixin author-imgs {
  @each $manly-man in $list
    .photo-#{$manly-man} {
        background: image-url("avatars/#{$manly-man}.png") no-repeat;

.author-bio {
    @include author-imgs();


Loops are essential and not difficult at all, and make Sass a more like a real programming language.


  • First of all thank you for sharing this informative blog.. This blog having more useful information that information explanation are step by step and very clear so easy and interesting to read.. After reading this blog i am strong in this topic which helpful to cracking the interview easily..

    php training course contents

Club-Mate, the beverage →