SCSS Control Directives
Control directives are powerful features in SCSS that allow you to write dynamic stylesheets using conditional statements and loops.
@if Directive
The @if directive allows you to conditionally output styles based on expressions.
// SCSS
@mixin theme($dark-theme: true) {
@if $dark-theme {
background-color: #333;
color: white;
} @else {
background-color: white;
color: #333;
}
}
.dark-mode {
@include theme(true);
}
.light-mode {
@include theme(false);
}
Output CSS:
.dark-mode {
background-color: #333;
color: white;
}
.light-mode {
background-color: white;
color: #333;
}
@for Directive
The @for directive allows you to generate repeated styles with variations.
// SCSS
@for $i from 1 through 3 {
.col-#{$i} {
width: $i * 25%;
}
}
Output CSS:
.col-1 {
width: 25%;
}
.col-2 {
width: 50%;
}
.col-3 {
width: 75%;
}
@each Directive
The @each directive is perfect for iterating through lists or maps.
// SCSS
$themes: (
'success': #28a745,
'warning': #ffc107,
'danger': #dc3545
);
@each $name, $color in $themes {
.alert-#{$name} {
background-color: lighten($color, 30%);
border: 1px solid $color;
color: darken($color, 20%);
}
}
Output CSS:
.alert-success {
background-color: #a3d7ab;
border: 1px solid #28a745;
color: #145523;
}
.alert-warning {
background-color: #fff3cd;
border: 1px solid #ffc107;
color: #997404;
}
.alert-danger {
background-color: #f8d7da;
border: 1px solid #dc3545;
color: #842029;
}
@while Directive
The @while directive creates styles in a loop until a condition is met.
// SCSS
$i: 6;
@while $i > 0 {
.heading-#{$i} {
font-size: $i * 0.25rem;
}
$i: $i - 1;
}
Output CSS:
.heading-6 { font-size: 1.5rem; }
.heading-5 { font-size: 1.25rem; }
.heading-4 { font-size: 1rem; }
.heading-3 { font-size: 0.75rem; }
.heading-2 { font-size: 0.5rem; }
.heading-1 { font-size: 0.25rem; }
Best Practices
- Use @if for conditional styling based on variables or settings
- Prefer @each over @for when working with lists or maps
- Use @for when you need numerical iterations
- Use @while sparingly, as @for and @each are usually more appropriate
- Keep your logic simple and maintainable