Welcome Guest! (App Version 3.1)

websitnero logo name

Sass Loops

Loops in Sass

In any programming language loops server the purpose of making iterations and some code is executed or some variable is altered per iteration. As CSS did not have any touch of proper programming language, Sass continuously enriched it with various features. For loops Sass adds 3 tools which can be used as per requirement:

  • @for
  • @each
  • @while

@for Loop

@for loop is the easiest of all loops and most used. This loop can be used to generate most commonly used classes in a project. For example, pad-10 may generate padding: 10, pad-20 may generate padding 20 and so on.

Look at the example below:


@for $i from 1 through 5 {
  .#{pad}-#{$i * 10} {
    padding: 10px * $i

main.css (compiled):

.pad-10 {padding: 10px;}
.pad-20 {padding: 20px;}
.pad-30 {padding: 30px;}
.pad-40 {padding: 40px;}
.pad-50 {padding: 50px;}

@each Loop

@each loop is very helpful in going through a set of values and then adding CSS styles based on these of values. Look at the example below:

$items: "hermione", "kate", "taylor";
@each $x in $items {
  .#{$x}-location {
    background-url: "../img/"+#{$x}+".png"

main.css (compiled):

.hermione-location {background-url: "../img/hermione.png";}
.kate-location {background-url: "../img/kate.png";}
.taylor-location {background-url: "../img/taylor.png";}

@while Loop

@while loop keeps looping and executing a set of code until the condition in the braces is being met. @while loop is one of the easiest loop to write and execute. Just take care that loop does not get to infinite due to missing condition.

Look at the example below:

$font-size: 10;

@while ($font-size <= 20) {
 .font-#{$font-size} {
    font-size: ($font-size * 1px);
  $font-size: $font-size + 1;

main.css (compiled):

.font-10 {font-size: 10px;}
.font-11 {font-size: 11px;}
.font-12 {font-size: 12px;}
.font-13 {font-size: 13px;}
.font-14 {font-size: 14px;}
.font-15 {font-size: 15px;}
.font-16 {font-size: 16px;}
.font-17 {font-size: 17px;}
.font-18 {font-size: 18px;}
.font-19 {font-size: 19px;}
.font-20 {font-size: 20px;}
WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.