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.

  1. Jeanine S. says:

    Hey, these examples for columns and themes were exactly what I was trying to look into! Thanks for the simple and straightforward code. Would love to see if you could autofeed your posts to Twitter so I can keep tabs on your content. Have a great day. 🙂

  2. Bruce P. says:

    Thanks for this tutorial, it was exactly what I needed! Hope your son felt better soon!

  3. trinitysenpai says:

    thanks for the tutorial!

  4. martindubenet says:

    Hi Gav,
    I’m not very good with arrays and looking for looping trought this multi-level array (sass map list) to generate CSS vars.

    But I don’t know how to approach the 2nd level of my array to make it render a css var for each existing `alphaValues`. I’m not even shure the `@each` controller is appropriate here.

    This type of sass map to get RGBa colors would be SO helpful.

    “`
    // array
    $rgbaColors: (primary, #67486b, alphaValues(70,50,20)), (secondary, #749ee8, alphaValues(60,30));

    :root{
    // css vars
    @each $colorName, $hexColor, $alphaValue in $rgbaColors {
    #{$alphaValue},
    –color-#{$colorName}-alpha-#{$alphaValue}: #{$hexColor * 0.001};
    }
    }
    “`

  5. Mario Elias says:

    Love this page. I like the @each loop example.

    QUESTION: how cam you change in order to get the output like this: .pink.class?

    Thank you Mario

  6. nicmare says:

    you can simply write width:$i * 10px;
    sass is relaxed!

  7. miran says:

    you literally made a cute webpage, which in the first glance seems so childish, but it gave me the what I wanted, knowledge in simplified manner.

    Still there is a possible modification in the website, about which we can discuss on mail.

Join the discussion!

You might like:

Create, register and use shortcodes in WordPress

Create, register and use shortcodes in WordPress

by Gav 18/03/2023

Learn how to create and register your own WordPress shortcodes to add dynamic content to your posts and pages.

How to use guard clauses in JavaScript

How to/why use guard clauses in JavaScript

by Gav 16/03/2023

Learn how to improve code readability and performance by using guard clauses in JavaScript. Discover their benefits and best practices.

Implements and Extends, Object Oriented TypeScript

Implements and Extends, Object Oriented TypeScript

by Gav 15/03/2023

Learn the difference between implements and extends in TypeScript. Use Implements to implement interfaces and types, and extends to inherit from classes.

Reading/Parsing and Writing YAML files in PHP, Symfony

Reading/Parsing and Writing YAML files, PHP Symfony

by Gav 14/03/2023

In this tutorial we will look at using YAML in PHP. Learn about Parsing and Writing YAML files using Symfony's YAML component.

Measuring code execution performance in JavaScript

Measuring code execution performance in JavaScript

by Gav 13/03/2023

Measuring code execution performance is an important way to identify bottlenecks. Use these methods in JavaScript to help optimise your code.

Measuring script/code execution time in PHP using microtime

Measuring script/code execution time in PHP, microtime

by Gav 06/03/2023

Find bottlenecks, optimise and clean your code, and speed up your apps by measuring the execution time of your PHP scripts using microtime.

Regenerate WordPress media image sizes, programmatically

Regenerate WordPress media image sizes, programmatically

by Gav 25/02/2021

Learn how to regenerate and update WordPress media and image sizes both programmatically (without plugin), and also with a handy plugin.

Magic Constants in PHP. What they are and how to use them.

Magic Constants in PHP. What they are and how to use them

by Gav 15/02/2021

Ever seen constants like __DIR__ and __FILE__ being used in PHP? These are 'Magic Constants', and this is how we can use them.

Detecting Keypress JavaScript

Detect single and multiple keypress events: JavaScript

by Gav 16/10/2019

Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!