SCSS by Example: Conditionals
Adding logic to stylesheets with this code example showing @if, @else if, and @else directives for conditional compilation, comparison operators, logical operators, and compile-time conditional CSS generation.
Code
$theme: dark;
body {
@if $theme == dark {
background-color: black;
color: white;
} @else if $theme == light {
background-color: white;
color: black;
} @else {
background-color: gray;
color: yellow;
}
}
// Conditional in mixin
@mixin text-color($bg-color) {
@if (lightness($bg-color) > 50%) {
color: black;
} @else {
color: white;
}
}
.button {
background-color: #3498db; // Dark blue
@include text-color(#3498db); // Sets color to white
}Explanation
SCSS provides control directives @if, @else if, and @else for conditional compilation of CSS rules. These directives evaluate expressions at compile time and include only the matching branch in the final CSS output. The condition can use comparison operators ==, !=, <, >, <=, >= and logical operators and, or, not to create complex boolean expressions.
Conditional directives enable powerful patterns like theme generation, responsive mixin logic, and automatic accessibility adjustments. The lightness() function returns a percentage value from 0% (black) to 100% (white), allowing automatic text color selection based on background luminance. This compile-time evaluation means the final CSS contains only the rules that matched the conditions, keeping the output lean.
Conditionals can be nested and combined with other control directives like loops. They are commonly used inside mixins and functions to create adaptive behavior based on parameters. The condition expression must evaluate to a boolean or truthy/falsy value, where false and null are falsy and all other values are truthy. This allows checking for variable existence or specific values in a single expression.
Code Breakdown
@if $theme == dark evaluates condition at compile time.@else if provides alternative condition when previous conditions are false.lightness($bg-color) > 50% uses built-in function in conditional expression.
