Skip to content
Related Articles

Related Articles

SASS @for and @while Rule
  • Last Updated : 15 Jul, 2020

@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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


AND

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

@while <expression> { 
    ... 
}

chevron_right


Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

@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);
}

chevron_right


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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :