//

SASS CONTROL DIRECTIVES

Sass control directives helps creating libraries for reuse and distribution, there by contribute to writing leaner Sass. Advanced frameworks use mixins. These mixins use directives such as @if, @for, each and @while.

These control directives will keep you from writing repetitive style declaration and condition logic, that might be the case with CSS.

@if

The @if control directive is useful conditional styling.

If the expression returns anything other than false, it will process its block of styles.

@mixin setBorderColor($state) {
    @if $state == 'important' {
        border-color: red;
    }
    @else {
        border-color: black;
    }
}

You can use this mixin as below:

.class-name {
   @include setBorderColor(important);
}

This will give us:

.class-name {
   border-color: red;
}

@for

The @for directive is a loop that has a start point and loops through to an endpoint. You can set @for to either cycle through the loop, or run from a starting point to an ending point.

The loop syntax is as follows:

@for $i from 1 through 12 {
    .column-#{$i} {
        width: 100% / 13 - $i;
    }
}

Using through will run the loop from the first iteration through the end. Using to will run each iteration in the loop until, but not including, the end iteration.

@each

@each loops through Sass variable lists to generate CSS.

The syntax looks like @each $var in.

Lets look at an example:

$align-list: center, left, right;

@each $align in $align-list {
    .txt-#{$align} {
        text-align: $align;
    }
}

The cimpiled CSS will look like:

.txt-center {
  text-align: center;
}

.txt-left {
  text-align: left;
}

.txt-right {
  text-align: right;
}

@while

The @while directive works similiarly to the @for directive, but instead of going through a list of values, the @while directive will run until the value returns false.

$btn-sizes: 6;
$btn-padding: 4px;

@while $btn-sizes > 0 {
  .btn-pad-#{$btn-sizes / 2} {
    padding: $btn-padding + $btn-sizes $btn-padding * $btn-sizes;
  }
  $btn-sizes: $btn-sizes - 2;
}

This code will be compiled into:

.btn-pad-3 {
    padding: 10px 24px;
}

.btn-pad-2 {
    padding: 8px 16px;
}

.btn-pad-1 {
    padding: 6px 8px;
}

Conclusion

All of these directives can end up saving you quite a bit of repetitive CSS. But use them sparingly, only when necessary.