Table of contents
1.
Introduction
2.
Control Directives and expressions in Sass
3.
Flow Control Rules
4.
if function
5.
@if Directive
5.1.
@if Directive
5.2.
@else-if Directive
6.
@for Directive
6.1.
through
6.2.
to
7.
@while Directive
8.
@each Directive
8.1.
@each Directive
8.2.
@each Directive with Multiple Assignments
8.3.
@each Directive with Multiple Assignments and maps
9.
FAQs
10.
Key Takeaways
Last Updated: Mar 27, 2024

Control Directives and expressions in Sass

Author Hari Sapna Nair
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Sass is a declarative scripting language, an extension to CSS. Despite that, it offers some limited procedural capabilities with the help of control directives and expressions in Sass.

Styling based on certain conditions or applying the same style many times with variations can be accomplished using control directives and expressions in Sass. They can be extremely useful while making large projects. 

 

This blog will explore more about control directives and expressions in Sass. We will discuss the if() function, @if directive, @for directive, @ for directive, @each directive, and @while directive in detail, along with various examples.

Control Directives and expressions in Sass

The control directives in Sass allow us to add conditional logic to the Sass code. They allow us to branch the code in different directions based on various conditions, and they will enable us to loop through code until specific conditions are true. 

Sass makes it easy to use mixins and extends to writing cleaner CSS. Using control directives, we can write better Sass code. Using the control directives like @if, @each, @for, and @while, we can make our Sass take on the brunt of what would otherwise require repetitive style declarations and conditional logic.

The control directives are used mainly in mixins. Control directives are part of compass libraries. They require flexibility, as they are a part of the Sass Compass libraries.

The directives allow us to include styles only if certain conditions are met or loop through sections of Sass code multiple times.

 

Control Directives and Expressions in Sass

Flow Control Rules

Sass provides several at-rules that help us control whether styles get emitted or emit them multiple times with slight variations. They are used in mixins and functions to write small algorithms to make writing our Sass code easier. Sass supports the following four flow control rules:

  • @if: It controls whether or not a block has to be evaluated.
  • @for: It evaluates a block a specific number of times.
  • @each: It evaluates a block for each element in a list or each pair in a map.
  • @while: It evaluates a block until a particular condition is met.

if function

Sass has a built-in if() function. It returns only one result from two possible outcomes. The function's result depends on whether the outcome is true or false.

 

Syntax

if(expression, val1, val2 )  

If the expression is true, the first value is considered; the second value is considered.
 

Example

Let's seen an example of the if function. In this example, if the condition is true, green will be the color of the text; else, it would be red.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Control Directives and Expressions in Sass</title>
 <link rel="stylesheet" href="styles.css" />
</head>
<body>
 <h1>Control Directives and Expressions in Sass</h1>
</body>
</html>

styles.scss

h1{ 
   color: if( 1 + 1 == 2 , green , red); 
} 

Now generate the css file using the following command.

sass --watch styles.scss:styles.css

styles.css

h1 {
 color: green;
}

 

Output

 

As the expression is true, green is selected as the color.

@if Directive

The @if directive is used to specify the execution of the code statements according to the result of the expression. Generally, the @if statement is used with multiple @if else statements and a single @else statement.

The two types of @if directive are:-

  • @if directive
  • @else if directive

@if Directive

The Sass @if directive accepts the SassScript expressions and uses the nested styles if the expression returns anything other than null or false.

 

Syntax

@if expression { 
 // Code
}

 

Example

Let's seen an example of the @if directive. In this example, the text color will be selected based on the several conditions given. We will be using the same index.html file here.

styles.scss

h1 { 
   @if 1 + 1 == 3 { color: green;} 
   @if 5 > 3      { color: red;} 
   @if null       { color: yellow;} 
}

styles.css

h1 {
 color: red; 
}

 

Output

 

As the second expression is true, red is selected as the color.

@else-if Directive

The @else-if directive is used when the @if directive does not satisfy the condition. If that too fails, the @else directive is used.

 

Syntax

@if expression {
 // Code
} @else if condition {
 // Code
} @else {
 // Code
}

 

Example

Let's seen an example of the @else-if directive. In this example, the text color will be selected based on the several if-else conditions given.

styles.scss

h1 { 
   @if 1 + 1 == 3 { color: red;} 
   @else if 5 < 3 { color: blue;} 
   @else if 6 > 4 { color: green;}
   @else          { color: yellow;} 
}

styles.css

h1 {
 color: green;
}

 

Output

 

As the first two expressions are false and the third one is true, green is selected as the color.

@for Directive

The @for directive allows us to generate a style in a loop. It is used when you require a repeatedly set of styles. It uses a counter variable to set the output for each iteration.

The two types of keywords used for the @for directive are:

  • through
  • to

through

In the @for directive, the through keyword specifies the range, including <start> and <end> values.
 

Syntax

@for $var from <start> through <end> 

 

Parameters:

  • $var: It specifies the name of the variable.
  • <start> and <end>: They are SassScript expressions that returns integers. If the <start> is lesser than <end> the counter variable will be incremented and when <start> is greater than <end> then the counter variable is decremented.

 

Example

In this example, the heading will have a different margin-left depending on the value of the “i” variable.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Control Directives and Expressions in Sass</title>
 <link rel="stylesheet" href="styles.css" />
</head>
<body>
 <h1 class = "heading1">Control Directives and Expressions in Sass</h1>
 <h1 class = "heading2">Control Directives and Expressions in Sass</h1>
 <h1 class = "heading3">Control Directives and Expressions in Sass</h1>
 <h1 class = "heading4">Control Directives and Expressions in Sass</h1>
</body>
</html>

styles.scss

@for $i from 1 through 4 { 
   .heading#{$i} { margin-left : $i * 10px; } 
}

styles.css

.heading1 {
 margin-left: 10px; }

.heading2 {
 margin-left: 20px; }

.heading3 {
 margin-left: 30px; }

.heading4 {
 margin-left: 40px; }

Output

to

The @for directive uses the to keyword, which specifies the range from the<start> value to the value before <end> value.

 

Syntax

@for $var from <start> to <end> 

 

Parameters:

  • $var: It specifies the name of the variable.
  • <start> and <end>: They are SassScript expressions that returns integers. If the <start> is lesser than <end> the counter variable will be incremented and when <start> is greater than <end> then the counter variable is decremented.
     

Example

In this example, the heading will have a different margin-left depending on the value of the “i” variable. Let's use the same index.html as above.

styles.scss

@for $i from 1 to 4 { 
   .heading#{$i} { margin-left : $i * 10px; } 
}

styles.css

.heading1 {
 margin-left: 10px; }

.heading2 {
 margin-left: 20px; }

.heading3 {
 margin-left: 30px; }

Output

 

In this example, the last heading is not affected.

@while Directive

The @while directive takes SassScript expressions, and until the statement evaluates to false, it repeatedly outputs the nested styles. Here the counter variable needs to be incremented or decremented on each iteration.
 

Syntax

while(condition) {
 // Code
}

 

Example

In this example, the heading will have a different margin-left depending on the value of the “i” variable. In this case, the last heading will be evaluated first. Let's use the same index.html as above.

styles.scss

$i: 4;
@while $i > 0 {
   .heading#{$i} { margin-left : $i * 10px; }
   $i: $i - 1;
}

styles.css

.heading4 {
 margin-left: 40px; }

.heading3 {
 margin-left: 30px; }

.heading2 {
 margin-left: 20px; }

.heading1 {
 margin-left: 10px; }

Output

@each Directive

The @each directive executes a set of items in either a list or a map. The three types of @each directive are:-

  • @each directive
  • @each directive with multiple assignments
  • @each directive with multiple assignments and maps

@each Directive

In the  @each directive, a variable is defined, which contains the value of each item in the list.

 

Syntax

@each $var in <list or map>

 

Parameters

  • $var: Represents the variable name. The @each rule will set $var to each item in a list and outputs the styles using the value of $var.
  • <list or map>: They are SassScript expressions that return a list or a map.
     

Example

In this example, the heading will have a different text color depending on the value of the item in the list. 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Control Directives and Expressions in Sass</title>
 <link rel="stylesheet" href="styles.css" />
</head>
<body>
 <h1 class = "heading-red">Control Directives and Expressions in Sass</h1>
 <h1 class = "heading-blue ">Control Directives and Expressions in Sass</h1>
 <h1 class = "heading-green ">Control Directives and Expressions in Sass</h1>
</body>
</html>

styles.scss

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

styles.css

.heading-red {
 color: red; }

.heading-blue {
 color: blue; }

.heading-green {
 color: green; }

 

Output

@each Directive with Multiple Assignments

In this multiple values are used with @each directive like $var1, $var2, $var3, ... in the <list>.

 

Syntax

@each $var1, $var2, $var3 ... in <list>

 

Parameters

  • $var1$var2, $var3, ... : They are the variable names. re
  • <list>: It represents list of lists, with each variable holding the element of the sub-lists.
     

Example

In this example, the heading will have a different text color and font style depending on the value of the item in the list. We will use the same index.html as above.

styles.scss

@each $color, $style in (red, normal), (blue, italic), (green, oblique) {
   .heading-#{$color} {
      color: #{$color};
      font-style: #{$style};
   }
}

styles.css

.heading-red {
 color: red;
 font-style: normal; }

.heading-blue {
 color: blue;
 font-style: italic; }

.heading-green {
 color: green;
 font-style: oblique; }

 

Output

@each Directive with Multiple Assignments and maps

The @each directive with multiple assignment works well with maps as well, and they are considered as lists of pairs. If we want to use the map, then we have to change the @each statement and use multiple assignments.

 

Syntax

@each $var1, $var2, $var3 in <map>

 

Parameters

  • $var1$var2, $var3, ...: They are the variable names. re
  • <map>: It represents the lists of pairs.

 

Example

In this example, the heading will have a different text color and font style depending on the values present in the map. We will use the same index.html as above.
styles.scss

@each $color, $style in (red: normal, blue: italic, green: oblique) {
   .heading-#{$color} {
      color: #{$color};
      font-style: #{$style};
   }
}

styles.css

.heading-red {
 color: red;
 font-style: normal; }

.heading-blue {
 color: blue;
 font-style: italic; }

.heading-green {
 color: green;
 font-style: oblique; }

 

Output

FAQs

  1. How are control directives triggered by CSS comments?
    CSS comments between declarations trigger the control directives. They support processing any node type and can target a set of nodes (block-syntax) or one node (self-closing). They are not triggered by at-rule parameters, comments inside selectors, or declaration values.
     
  2. When should we use the @if directive and the @while directive?
    The @if directive is used to execute a set of statements a single time based on a boolean expression. 
    The @while directive is used to execute the statements multiple times and control their execution based on a specific condition.
     
  3. Why are control directives and expressions in Sass used?
    Control directives and expressions are used to include styles under specific conditions or the same style several times with some variations. 
     
  4. What is the difference between the two forms of @for directive?
    The" two forms of the @for directive use the "through and "to" keyword. The "through" keyword loops and includes the ending value, whereas the "to" keyword does not include the ending value.
     
  5. How does the @if directive work?
    The @if directive takes an expression, evaluates it as true or false, and runs or doesn't run the code based on the evaluation. It allows us to create different branches in our code that run under different conditions.

Key Takeaways

This blog covered the control directives and expressions in Sass. We discussed the if() function, @if directive, @for directive, @ for directive, @each directive, and @while directive in detail, along with various examples. Using these directives can save us quite a bit of repetitive CSS.

 

Don't stop here! Check out some fantastic blogs on Sass like Sass- Introduction, Sass-Installation, and Usage, etc.

We hope you found this blog on control directives and expressions in Sass useful. Liked the blog? Then feel free to upvote and share it.

Live masterclass