Flow Control

Sass supports a number of flow control directives.
@if :Nothing will be returned if the evaluation returns 'null' or 'false'.
$type: monster;
p {
   @if 1 + 1 == 2 { border: 1px solid;  }
   @if 5 < 3      { border: 2px dotted; }
   @if null       { border: 3px double; }
   @if $type == ocean {
      color: blue;
   } @else if $type == matador {
      color: red;
   } @else if $type == monster {
      color: green;
   } @else {
      color: black;
   }
}

p { border: 1px solid; color: green; }
@for: from...to results in one less iteration than from...through.
@for $i from 1 through 3 {
  .item-#{$i} { width: 2em * $i; }
}
@for $i from 1 to 3 {
  .list-#{$i} { width: 5em * $i; }
}

.item-1 { width: 2em; } .item-2 { width: 4em; } .item-3 { width: 6em; } .list-1 { width: 5em; } .list-2 { width: 10em; }
@each: is used to iterate through lists and maps.
@each $animal, $color, $cursor in (puma, black, default),
                                  (sea-slug, blue, pointer),
                                  (egret, white, move) {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
    border: 2px solid $color;
    cursor: $cursor;
  }
}
@each $header, $size in (h1: 2em, h2: 1.5em, h3: 1.2em) {
  #{$header} {
    font-size: $size;
  }
}

.puma-icon { background-image: url("/images/puma.png"); border: 2px solid black; cursor: default; } .sea-slug-icon { background-image: url("/images/sea-slug.png"); border: 2px solid blue; cursor: pointer; } .egret-icon { background-image: url("/images/egret.png"); border: 2px solid white; cursor: move; } h1 { font-size: 2em; } h2 { font-size: 1.5em; } h3 { font-size: 1.2em; }
@while: loops until the expression evaluates to false.
$i: 6;
@while $i > 0 {
  .item-#{$i} { width: 2em * $i; }
  $i: $i - 2;
}

.item-6 { width: 12em; } .item-4 { width: 8em; } .item-2 { width: 4em; }