Structures de contrôle

Pour simplifier la création de règles répétitives ou conditionnelles, SASS intègre plusieurs structures de contrôle.

Méthodeif

1
p{
2
  @if $nb > 10 {
3
    color: black;
4
  } @else {
5
    color: white;
6
  }
7
}

Définitioneach

each permet de réaliser une boucle à partir d'une liste

1
$liste: (1, 2, 3, 4);
2
@each $element in $liste{
3
  .col-#{$element} {
4
    width: (100px * $element);
5
  }
6
}

Attention à l'interpolation dans la chaîne de caractère.

Ce qui donne

1
.col-1 {
2
  width: 100px;
3
}
4
.col-2 {
5
  width: 200px; 
6
}
7
.col-3 {
8
  width: 300px; 
9
}
10
.col-4 {
11
  width: 400px;
12
}

each avec une map

1
$map: (1: 50px, 2: 75px, 3: 80px, 4: 150px);
2
@each $key, $value in $map{
3
  .col-#{$key} {
4
    width: $value;
5
  }
6
}

Ce qui donne

1
.col-1 {
2
  width: 50px;
3
}
4
.col-2 {
5
  width: 75px; 
6
}
7
.col-3 {
8
  width: 80px; 
9
}
10
.col-4 {
11
  width: 150px;
12
}

Définitionfor

Les boucles avec compteur

1
@for $i from 1 through 4{
2
  .col-#{$i} {
3
    width: (100px * $i);
4
  }
5
}

Ce qui donne

1
.col-1 {
2
  width: 100px;
3
}
4
.col-2 {
5
  width: 200px; 
6
}
7
.col-3 {
8
  width: 300px; 
9
}
10
.col-4 {
11
  width: 400px;
12
}