Control Directives in Sass
Sass provides powerful control directives that allow you to create more dynamic and flexible stylesheets. In this guide, we'll explore the @if, @else, and conditions, @for and @each loops, as well as the @while directive, along with examples for each.
1. @if, @else, and Conditions:
- @if Directive:
The @if directive is used to conditionally apply styles based on a specified condition.
Example:
$theme: light;
.button {
@if $theme == light {
background-color: #fff;
color: #333;
} @else {
background-color: #333;
color: #fff;
}
}- @else Directive:
The @else directive follows an @if directive and provides an alternative set of styles if the condition is not met.
Example:
$font-size: 16px;
.text {
@if $font-size > 18px {
font-weight: bold;
} @else {
font-style: italic;
}
}2. @for and @each Loops:
- @for Loop:
The @for directive allows you to generate styles in a loop, iterating over a range of values.
Example:
// Generate classes with different font sizes
@for $i from 1 through 3 {
.font-size-#{$i} {
font-size: $i * 10px;
}
}- @each Loop:
The @each directive iterates over each item in a list or map, allowing you to apply styles dynamically.
Example:
$colors: (primary: #3498db, secondary: #2ecc71, accent: #e74c3c);
@each $key, $value in $colors {
.color-#{$key} {
background-color: $value;
}
}3. @while Directive:
- @while Directive:
The @while directive creates a loop that continues as long as a specified condition is true.
Example:
$i: 1;
@while $i < 5 {
.box-#{$i} {
width: $i * 20px;
height: $i * 20px;
}
$i: $i + 1;
}In this example, the @while loop generates classes for boxes with increasing sizes until $i is no longer less than 5.
Conclusion:
Sass control directives provide a way to introduce logic and iteration into your stylesheets, making them more dynamic and adaptable. By using @if, @else for conditions, @for and @each for loops, and @while for dynamic iteration, you can create styles that respond to different conditions or generate repetitive patterns efficiently. These control directives offer a powerful set of tools to enhance the expressiveness and functionality of your Sass styles.