Conditions
With conditions, it’s possible to check certain information in our SCSS file. For example, if the color is equal to orange, then we define new parameters:
// définition des variables '$shadow' et '$color'
$shadow: '"';
$color: orange;
// Si $color est égale à 'orange'
@if ($color == orange) {
// Alors shadow vaut :
$shadow: 0 0 5px black
}
// Sinon si $color est égale à 'blue'
@elseif ($color == blue) {
// Il est également possible de redéfinir la variable
$color: pink;
$shadow: 0 5px 0 red;
}
// Sinon, $shadow prendra les valeurs
@else {
$shadow: 5px 5px white;
}
.maClass {
color: $color;
box-shadow: $shadow;
}
Generated CSS :
.maClass {
color: orange;
box-shadow: 0 0 5px black;
}
Thanks to this condition, it’s possible to change the value of $shadow by setting $color. In this example, we check the value of $color, however, several other comparisons are possible. Discover all the control directives of SASS.
Loops
Loops allow you to repeat an instruction as many times as you want.
Loops @for
@for $i from 1 through 6 {
.grid-#{$i} {
width: 100px*$i;
}
}
Generated CSS :
.grid-1 { width: 100px; }
.grid-2 { width: 200px; }
.grid-3 { width: 300px; }
.grid-4 { width: 400px; }
.grid-5 { width: 500px; }
.grid-6 { width: 600px; }
Loops @while
$i: 6;
@while $i > 0 {
.item-#{$i} { width: 2em * $i; }
$i: $i - 2;
}
Generated CSS :
.item-6 { width: 12em; }
.item-4 { width: 8em; }
.item-2 { width: 4em; }
Loops @each
// @each permet de parcourir une liste :
@each $animal in puma, sea-slug, egret, salamander {
.#{$animal}-icon {
background-image: url('/images/#{$animal}.png');
}
}
Generated CSS :
.puma-icon {
background-image: url('/images/puma.png');
}
.sea-slug-icon {
background-image: url('/images/sea-slug.png');
}
.egret-icon {
background-image: url('/images/egret.png');
}
.salamander-icon {
background-image: url('/images/salamander.png');
}
This list can be defined in a variable (comparable to arrays in PHP). Each value must be separated by a comma.
Example: $var: puma, sea-slug, egret, salamander;