The goal of this tutorial is to guide you through looping through maps and lists in SASS/SCSS. We'll be exploring the use of the @each
and @for
control directives which are powerful features of SASS/SCSS.
In this tutorial, you'll learn:
@each
and @for
.The prerequisite for this tutorial is a basic understanding of SASS/SCSS and CSS.
In SASS/SCSS, a list is a series of values separated by spaces or commas. Maps are similar to lists but they're key-value pairs.
To loop through a list, we use the @each
directive in SASS/SCSS. The @each
directive takes a variable and a list, then generates a styles block for each item in the list.
Just like lists, we can loop through maps using the @each
directive. This time it takes two variables, one for the key and one for the value.
@for
DirectiveThe @for
directive is used to create a loop from one number to another number.
Consider the following code snippet:
$colors: red, blue, green;
@each $color in $colors {
.text-#{$color} {
color: $color;
}
}
In the snippet above, we've created a list of colors and looped through them. For each color, we generate a class .text-color
that sets the text color to that color.
The generated CSS will look like this:
.text-red {
color: red;
}
.text-blue {
color: blue;
}
.text-green {
color: green;
}
Here's a code snippet where we loop through a map:
$font-sizes: ("small": 12px, "medium": 14px, "large": 16px);
@each $key, $value in $font-sizes {
.text-#{$key} {
font-size: $value;
}
}
In this code, we loop through the $font-sizes
map and for each key-value pair, we generate a class that sets the font size.
The generated CSS will look like this:
.text-small {
font-size: 12px;
}
.text-medium {
font-size: 14px;
}
.text-large {
font-size: 16px;
}
@for
DirectiveBelow is an example of using the @for
directive:
@for $i from 1 through 3 {
.col-#{$i} {
width: $i * 33.33%;
}
}
This code will generate CSS for three columns, each with a width one third of the parent.
In this tutorial, you've learned how to loop through lists and maps in SASS/SCSS using the @each
and @for
directives.
For further learning, you can explore other control directives provided by SASS/SCSS such as @while
and @if
.
Solution:
```scss
$colors: red, blue, green, yellow, black;
@each $color in $colors {
.bg-#{$color} {
background-color: $color;
}
}
```
Solution:
```scss
$font-sizes: ("small": 10px, "medium": 16px, "large": 24px);
@each $key, $value in $font-sizes {
.font-#{$key} {
font-size: $value;
}
}
```
@for
directive to generate 10 classes that set the margin-top from 10px to 100px in increments of 10px.Solution:
scss
@for $i from 1 through 10 {
.mt-#{$i} {
margin-top: $i * 10px;
}
}
Keep practicing and exploring more features of SASS/SCSS to enhance your web development skills.