SASS / SCSS
Beginner
1 min read
@if, @else if, and @else Directives
Example
// ── @if / @else if / @else in a mixin ────────────────────────────────────────
@mixin theme-colors($theme) {
@if $theme == 'light' {
background: #ffffff;
color : #333333;
border : 1px solid #e0e0e0;
} @else if $theme == 'dark' {
background: #1a1a2e;
color : #e0e0e0;
border : 1px solid #444;
} @else if $theme == 'sepia' {
background: #fdf6e3;
color : #5c4b37;
border : 1px solid #d4c5a9;
} @else {
@warn "Unknown theme `#{$theme}`. Falling back to light.";
background: #ffffff;
color : #333333;
}
}
.page-light { @include theme-colors('light'); }
.page-dark { @include theme-colors('dark'); }
.page-sepia { @include theme-colors('sepia'); }
// ── @if for type checking in a function ──────────────────────────────────────
@use 'sass:meta';
@use 'sass:math';
@function to-rem($value) {
@if meta.type-of($value) != 'number' {
@error "to-rem() expects a number, got #{meta.type-of($value)}.";
}
@if math.is-unitless($value) {
@return ($value / 16) * 1rem;
} @else if math.unit($value) == 'px' {
@return math.div($value, 16px) * 1rem;
} @else if math.unit($value) == 'rem' {
@return $value; // already rem
} @else {
@error "to-rem() cannot convert unit `#{math.unit($value)}`.";
}
}
// ── Ternary-style if() function ───────────────────────────────────────────────
$dark-mode: false;
.text {
color : if($dark-mode, #ecf0f1, #2c3e50);
background : if($dark-mode, #2c3e50, #ffffff);
}
Related Resources
SASS / SCSS Reference
Complete tag & property list
SASS / SCSS How-To Guides
Step-by-step practical guides
SASS / SCSS Exercises
Practice what you've learned
More in SASS / SCSS