DEV Community

mikkel250
mikkel250

Posted on

Sass Control Flow

If Else

Sass gives more control flow than CSS, beginning with the form of @if and @else. Based on the results of the control flow, the Sass will compile to different CSS based on the conditions.

@mixin foo($size) {
  font-size: $size;
  @if $size > 20 {
    line-height: $size;
  } @else {
    // @else shown as syntax demo, no need for it here
  }
}

.small {
  @include foo(14px);
}
.large {
  @include foo(24px);
}

// compiles to CSS
.small {
  font-size: 14px;
}
.large {
  font-size: 24px;
  line-height: 24px;
}

If you work with any other programming language, this should look familiar, just note that there are no parentheses around the condition following the @if keyword.

For loops

Sass also provides a for loop that can be used for control flow and automate repetitive tasks. Some things to note are that for loops can be either inclusive or exclusive, depending on how it is written. Using through is inclusive. Using to is exclusive.

@for $i from 1 through 5 {
 // inclusive
}

@for $i from 1 to 5 {
 // exclusive
}

The syntax of how to create style rules for different font sizes for the various h tags based on some simple math is shown below. On the second line of the example below, the #{$i} is interpolation, which tacks on the value of i after the h.

@for $i from 1 through 5 {
  h#{$i} {
    font-size: 5rem - $i*0.75rem;
  }
}

// compiles to CSS 
h1 {font-size: 4.25rem;}
h2 {font-size: 3.5rem;}
h3 {font-size: 2.75rem;}
h4 {font-size: 2rem;}
h5 {font-size: 1.25rem;}

Another good application of a loop might be if a grid system is used, a more DRY method could use a loop to generate the values instead of repeatedly writing the measurement values, and later being able to change the values once and have them reflected everywhere.

Each

Another loop which can be used is @each, which is used to iterate over lists, which will be covered in the next installment in this series. The syntax is:

@each $i in $myList {
  /* your code */ 
}

Top comments (0)