In this tutorial, we will explore the power of SASS/SCSS by learning how to loop through variables using the @each and @for directives. These directives are helpful when you want to generate repetitive CSS with different values.
By the end of this tutorial, you will learn:
Prerequisites:
The @each directive takes a list or map and generates styles for each item. It's useful for writing repetitive CSS where each repetition has a different value.
The @for directive creates styles in a loop, just like a regular programming loop. It takes a start and end value and iterates over that range.
$colors: red, blue, green;
@each $color in $colors {
.text-#{$color} {
color: $color;
}
}
In this example, we have a list of color names. The @each directive loops over each color and generates a CSS class for each one. The output CSS will be:
.text-red {
color: red;
}
.text-blue {
color: blue;
}
.text-green {
color: green;
}
@for $i from 1 through 3 {
.col-#{$i} {
width: $i * 33.333%;
}
}
In this example, the @for directive is used to generate grid classes. The loop runs from 1 through 3 and generates a CSS class for each iteration. The output CSS will be:
.col-1 {
width: 33.333%;
}
.col-2 {
width: 66.666%;
}
.col-3 {
width: 100%;
}
In this tutorial, we learned how to use the @each and @for directives in SASS/SCSS to create loops in your stylesheets. We also saw practical examples of how to use these directives.
Next steps for learning would be to dive deeper into SASS/SCSS features like functions, mixins, and conditionals.
Additional resources:
Generate a series of padding classes (p-1, p-2, ..., p-5) where each class increases the padding by 5px.
@for $i from 1 through 5 {
.p-#{$i} {
padding: $i * 5px;
}
}
In this solution, we loop from 1 through 5 and for each iteration, we generate a padding class that increases the padding by 5px.
Using the @each directive, create a series of background color classes given a list of colors.
$colors: red, blue, green, yellow, orange;
@each $color in $colors {
.bg-#{$color} {
background-color: $color;
}
}
In this solution, we loop through each color in the list and generate a background color class for each one.
Keep practicing these concepts to get more comfortable with SASS/SCSS. Happy coding!