This tutorial aims to help you understand how to use control structures in SASS/SCSS to write more efficient and maintainable stylesheets.
By following this tutorial, you'll get a grasp of:
Basic knowledge of CSS and a general understanding of SASS/SCSS.
In SASS/SCSS, control structures are used to create complex stylesheets while keeping the code DRY (Don't Repeat Yourself) and maintainable. Control directives provide you with the ability to use standard programming constructs such as if
, for
, each
, and while
loops in your SASS/SCSS code.
@for $i from 1 through 3 {
.item-#{$i} { width: 2em * $i; }
}
This loop will generate three classes, .item-1
, .item-2
, and .item-3
, each with a different width.
for
and each
loops to avoid repeating codeif
directives to create conditional styles// for loop to style list items differently
@for $i from 1 through 5 {
.item-#{$i} {
background-color: lighten(red, $i * 10%);
}
}
This will create five classes, each with a different background color.
// define a list of colors
$colors: red, blue, green, yellow, purple;
// each loop to apply colors
@each $color in $colors {
.text-#{$color} {
color: $color;
}
}
This will create five classes, .text-red
, .text-blue
, etc., each with a different text color.
In this tutorial, we've learned:
for
and each
loopsFor further learning, consider exploring more complex use cases of control structures and try using them in a real project.
Write a SASS/SCSS for
loop to generate ten classes, .col-1
through .col-10
, each with a different width defined as a percentage (10% to 100%).
Define a list of web-safe font families and use an each
loop to generate classes for each one.
// for loop to generate column classes
@for $i from 1 through 10 {
.col-#{$i} {
width: $i * 10%;
}
}
// define a list of font families
$fonts: Arial, Verdana, Helvetica, Times, Courier, Georgia;
// each loop to generate font classes
@each $font in $fonts {
.font-#{$font} {
font-family: $font;
}
}
Remember, practice is key to mastering any programming language or framework. Keep experimenting with different control structures and use cases. Happy coding!