JS-Sass Loops
@for
@for is used in two ways: "start through end" or "start to end". The main difference is that "start to end" excludes the end number, and "start through end" includes the end number.
"Start through end" example:
<style type='text/sass'>
@for $i from 1 through 5 {
.text-#{$i} { font-size: 10 * $i; }
}
</style>
<p class="text-1">Hello</p>
<p class="text-2">Hello</p>
<p class="text-3">Hello</p>
<p class="text-4">Hello</p>
<p class="text-5">Hello</p>
f-s will be 10px, 20px, 30px, 40px 50px respectively.
@each
On each iteration, the variable gets assigned to the current value from the list or map.
<style type='text/sass'>
@each $color in blue, black, red {
.#{$color}-bg {background-color: $color;}
}
div {
height: 200px;
width: 200px;
}
</style>
<div class="blue-bg"></div>
<div class="black-bg"></div>
<div class="red-bg"></div>
We Wrote an @each directive that goes through a list:
blue, black, red and assigns each variable to a .color-bg class,
where the "color" part changes for each item.
@while
<style type='text/sass'>
$x: 1;
@while $x < 4{
.text-#{$x} { font-size: 5px * $x;}
$x: $x + 1;
}
</style>
<p class="text-1">Hello</p>
<p class="text-2">Hello</p>
<p class="text-3">Hello</p>
Comments