Contact!

For, Each and While loops in Sass and SCSS

for, each and while loops in Sass

Sass has several loop options, much like other programming languages. They include the @for loop, @each loop and @while loop. These loops are an incredibly powerful tool for generating CSS code because you can defer code generation into an iterable task.

You’ll notice that for all of these examples I’m using string interpolation.

@for loop

This is basically a simple iterator loop for Sass.

When I was stupid enough to write my own grid framework I used an @for loop to generate code for columns.

$columns: 5;

@for $i from 1 through $columns {
    .columns-#{$i} {
        width: (100% / $i);
    }
}

This example iterates from 1 to the number of columns, returning $i as the current position in the loop. If you are interested in the column code you can check out gavsgrid on GitHub.

/* Output */

.columns-1 {
    width: 100%; 
}

.columns-2 {
    width: 50%; 
}

.columns-3 {
    width: 33.33333%; 
}

.columns-4 {
    width: 25%; 
}

.columns-5 {
    width: 20%; 
}

@each loop

The @each loop iterates each value in an array. The example below returns a key ‘$themeColour’, but you can omit this if you don’t need a key returned.

In the day job I use an @each loop for iterating through theme colours (there are many and I’m lazy).

$themeColours: (
    "pink": #DC51AC,
    "red": #D64651,
    "orange": #E55937,
);

@each $themeColour, $i in $themeColours {
    body {
        &.#{$themeColour} {
            background-color: $i;
        }	
    }
}

In this example the ‘$themeColour’ returns the key so that I can use it to check for the class on the body. ‘$i’ is the value (colour hex in this case) which is used to colour the background depending on which theme colour is being used.

/* Output */

body.pink {
    background-color: #DC51AC; 
}

body.red {
    background-color: #D64651; 
}

body.orange {
    background-color: #E55937; 
}

@while loop

A while loop is simply conditional. It will execute until a given condition is met. I’ve never really had a legitimate use for this, although I’m sure there are plenty… Here is something silly:

$count: 0;

@while $count < 5 {
    .length-#{$count} {
        width: (10 * $count) + px;
    }

    $count: $count + 1;
}

Here we loop 5 times creating 5 separate length classes. The width is 10 times the count.

/* Output */

.length-0 {
    width: 0px; 
}

.length-1 {
    width: 10px; 
}

.length-2 {
    width: 20px; 
}

.length-3 {
    width: 30px; 
}

.length-4 {
    width: 40px; 
}

I never thought that I would be writing a blog post while sitting in the dark on my son’s bedroom floor. He’s running a temperature and not feeling very well; I don’t want to leave him on his own… poor kid.

Join the discussion!

You might like: