Open In App

SASS @for Rule

Improve
Improve
Like Article
Like
Save
Share
Report

The @for rule in SASS is used to count up or down from one number to another and check the section for every number that comes in between the given range. Every number is assigned a variable name that can be accessed in the loop. It can be used in two ways:

1. start through end: In this type, the “start through end” includes the end number as part of the count.

Syntax:

@for <variable> from <expression> through <expression> {

    /* Body of loop that will be executed 
    when the condition is true */
}

Example: In this example, we will use the through syntax. The #{$i} part is the syntax to combine a variable (i) with text to make a string.

@for $i from 1 through 3 {
    .col-#{$i} { width: 100%/3 * $i; }
}

Output:

.col-1 {
  width: 33.3333333333%;
}

.col-2 {
  width: 66.6666666667%;
}

.col-3 {
  width: 100%;
}

2. start to end: In this type, the “start to end” excludes the end number as part of the count.

Syntax:

@for <variable> from <expression> to <expression> {

    /* Body of loop that will be executed 
       when the condition is true */
}

Example:

@for $i from 1 to 5 {
  .column-#{$i} { width: 100%/4 * $i; }
}

Output:

.column-1 {
  width: 25%;
}

.column-2 {
  width: 50%;
}

.column-3 {
  width: 75%;
}

.column-4 {
  width: 100%;
}

Last Updated : 07 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads