Table of Contents
Sass (Syntactically Awesome Stylesheets) is a powerful CSS preprocessor that extends CSS with features like variables, mixins, conditionals, and loops. These features allow developers to write more dynamic and maintainable stylesheets. Understanding how to use conditionals and loops in Sass can significantly enhance your styling workflow.
Understanding Sass Conditionals
Conditionals in Sass enable you to apply styles based on specific conditions. They are similar to if-else statements in programming languages. Sass provides the @if directive to implement conditionals.
For example, you can change styles depending on a variable’s value:
@$theme: dark;
body {
@if $theme == dark {
background-color: #222;
color: #fff;
} @else {
background-color: #fff;
color: #000;
}
}
Using Loops in Sass
Loops in Sass allow you to generate repetitive styles efficiently. Sass supports @for, @each, and @while loops. These are useful for creating grid systems, multiple classes, or repetitive styles.
For example, to create classes for a series of spacing utilities:
@for $i from 1 through 5 {
.margin-#{$i} {
margin: #{$i * 10}px;
}
}
Practical Example: Dynamic Button Styles
Suppose you want to style buttons differently based on their type (primary, secondary, etc.) and generate multiple size variants. You can combine conditionals and loops for this task.
$button-types: primary, secondary, danger;
$sizes: small, medium, large;
@each $type in $button-types {
@each $size in $sizes {
.btn-#{$type}-#{$size} {
@if $type == primary {
background-color: blue;
color: white;
} @else if $type == secondary {
background-color: gray;
color: black;
} @else if $type == danger {
background-color: red;
color: white;
}
@if $size == small {
padding: 4px 8px;
font-size: 12px;
} @else if $size == medium {
padding: 8px 16px;
font-size: 14px;
} @else if $size == large {
padding: 12px 24px;
font-size: 16px;
}
}
}
}
Using conditionals and loops together streamlines your stylesheet and makes it adaptable to new themes or components with minimal code duplication.
Summary
In Sass, conditionals like @if allow for styling based on variable values, while loops like @for and @each help generate repetitive styles efficiently. Mastering these features enables you to create more dynamic, scalable, and maintainable stylesheets for your web projects.