Open In App

SASS @for and @while Rule

Improve
Improve
Like Article
Like
Save
Share
Report

@for rule 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 given variable name. In order to exclude the last number, use to and in order to include it, use through.

Syntax:




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


AND




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


Example:




$gfg: green;
  
@for $i from 1 through 5 {
  ul:nth-child(2n + #{$i}) {
    background-color: darken($gfg, $i * 5%);
  }
}


Output:

ul:nth-child(2n+1) {
  background-color: #006700;
}

ul:nth-child(2n+2) {
  background-color: #004d00;
}

ul:nth-child(2n+3) {
  background-color: #003400;
}

ul:nth-child(2n+4) {
  background-color: #001a00;
}

ul:nth-child(2n+5) {
  background-color: #000100;
}

@while rule analysis the section only if the given expression is true. The section continues compiling until it returns false, then the section stops compilation.

Syntax:




@while <expression> { 
    ... 
}


Example:




@function scale-below($value, $base, $ratio: 2) {
  @while $value > $base {
    $value: $value / $ratio;
  }
  @return $value;
}
  
$normal-font-size: 22px;
gfg {
  font-size: scale-below(20px, 12px);
}


Output:

gfg {
  font-size: 10px;
}

Truthiness And Falseness: Some other values can also be used anywhere, true or false are allowed. The values false and null means that the Sass considers them to show falseness and which causes the conditions to fail. Every other value is true. So Sass considers them to succeed with the conditions. Some languages consider some more values for falseness than just false and null, not including Sass in that list. Empty strings, empty lists, and the number 0 are all considered truth in Sass.



Last Updated : 15 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads