Using conditionals in SCSS allows you to apply styles based on specific conditions, making your code more dynamic and flexible. With @if, @else if, and @else, you can control how styles are generated depending on variables or logic. This is useful for handling themes, color variations, or different layout behaviors. It helps reduce repetition by applying styles only when certain conditions are met. Overall, SCSS conditionals improve control, readability, and maintainability of your stylesheets.
What Are Conditionals in SCSS?
Conditionals let you apply styles based on logic. Using @if, @else if, and @else, you can control how styles are generated dynamically.
Example:
$theme: dark;
body {
@if $theme == dark {
background: #000;
color: #fff;
} @else {
background: #fff;
color: #000;
}
}
Using @if Statement
The @if statement checks a condition and applies styles only if the condition is true.
Example:
$size: large;
.box {
@if $size == large {
padding: 20px;
}
}
Using @else if for Multiple Conditions
You can check multiple conditions using @else if to handle different cases.
Example:
$status: warning;
.alert {
@if $status == success {
background: green;
} @else if $status == warning {
background: orange;
} @else {
background: red;
}
}
Using Conditionals with Functions
Conditionals are often used inside functions to return dynamic values.
Example:
@function text-color($bg) {
@if lightness($bg) > 50 {
@return black;
} @else {
@return white;
}
}
.box {
background: #222;
color: text-color(#222);
}
Real-World Usage (Dynamic Styling)
Conditionals help build flexible design systems like themes, responsive styles, and reusable components.
Example:
@mixin button($type) {
@if $type == primary {
background: blue;
color: white;
} @else if $type == secondary {
background: gray;
color: white;
}
}
.btn {
@include button(primary);
}



