sass
  1. sass-control-directives

SASS Control Directives

SASS provides a number of control directives, which help to write more dynamic, parameterized and efficient code.

Syntax

The following are the control directives available in SASS:

  • @if - The @if directive allows you to declare conditional statements in your SASS code.

    Syntax:

    @if (condition) {
        //content to be executed if condition is true
     } 
     @else if (condition2) { // optional
         //content to be executed if condition2 is true
     } 
     @else {
         //content to be executed if both the conditions are false
    }
    
  • @for - The @for directive is used for declaring loops in your SASS code.

    Syntax:

    @for $variable from start to end {
        //content to be looped
    }
    

    Example:

    @for $i from 1 to 5 {
        .col-#{$i} { width: 20% * $i; }
    }
    

    Output:

    .col-1 { width: 20%; }
    .col-2 { width: 40%; }
    

.col-3 { width: 60%; } .col-4 { width: 80%; } .col-5 { width: 100%; }


- **@each** - The @each directive is used to loop over a collection.

Syntax:

@each $variable in collection { //content to be looped }


Example:

@each $color in red, green, blue { .#{$color}-text { color: $color; } }

Output:

.red-text { color: red; } .green-text { color: green; } .blue-text { color: blue; }


- **@while** - The @while directive is used to declare a while loop in SASS.

Syntax:

@while (condition) { //content to be looped }


## Explanation

- The @if allows for conditional statements and executes a block of code if the condition is true.
- The @for directive is used to declare loops based on a range defined by the starting and ending values of a variable.
- The @each directive is used to loop through each value of a collection.
- The @while directive allows you to declare a loop that will continue to execute as long as the condition provided remains true.

## Use

The SASS control directives can be used as per the requirements in SASS code to make the code more dynamic, efficient and modularized.

## Important Points

- The control directives are used to make the code more readable and efficient.
- The condition in @if, @else if and @while must be enclosed in parentheses.
- The @for directive loops until the end value but does not include the end value.
- The @each directive can be used to loop through lists, maps, or even CSS selectors.

## Summary

SASS control directives are a powerful tool for making code more efficient, modularized and dynamic. Using these directives, you can create loops, conditional statements and more, which helps in creating cleaner and more readable code. They provide the programmer with more contol over the code and help to simplify it.
Published on: