Performance: @else and @else if branches
This affects CSS compilation time and the size of the generated CSS file, which impacts page load speed.
@if $font-scale >= 1.5 { h1 { font-size: 3rem; } } @else if $font-scale >= 1.0 { h1 { font-size: 2rem; } }
@if $font-scale >= 1.5 { h1 { font-size: 3rem; } } @if $font-scale >= 1.0 { h1 { font-size: 2rem; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Separate @if statements | N/A | N/A | Larger CSS file increases parsing time | [X] Bad |
| @if with @else if branches | N/A | N/A | Smaller CSS file reduces parsing time | [OK] Good |
@else if branch do in Sass?@if and @else if roles@if checks the first condition. If false, @else if checks another condition.@else if behavior@else if only runs if the previous @if or @else if was false, allowing multiple checks.@if was false -> Option D@else if = checks next condition [OK]@else if checks next condition only if previous fails [OK]@else if runs when previous is true@else if with @else@else if ends the condition chain@else if in Sass?@else if syntax@else if is written as two words without parentheses around the condition.@else if $color == red { ... }. @elseif $color == red { color: red; } misses space. @else if ($color == red) { color: red; } uses parentheses which Sass does not require. @else if $color = red { color: red; } uses single equals which is assignment, not comparison.@else if syntax = @else if $color == red { color: red; } [OK]@else if [OK]@elseif as one word$color: blue;
@if $color == red {
background: red;
} @else if $color == green {
background: green;
} @else {
background: black;
}$color$color is set to blue.@if checks if $color == red (false). Then @else if checks if $color == green (false). Since both are false, @else runs, setting background to black.@else runs = black [OK]@if or @else if matches, @else runs [OK]@else if runs when condition is false@else is optional and skipped@if $size == large {
font-size: 2rem;
} @else if $size = medium {
font-size: 1.5rem;
} @else {
font-size: 1rem;
}== to compare values, not single equals = which assigns values.@else if line uses $size = medium which is assignment, causing a syntax error.@else if -> Option C$theme is set to null?$theme: null;
@if $theme == light {
background: white;
} @else if $theme == dark {
background: black;
} @else {
background: gray;
}null in Sass conditionsnull is a special value that does not equal strings like light or dark.$theme = null@if $theme == light and @else if $theme == dark are false. So, @else runs, setting background to gray.null matches no condition, so @else runs [OK]null never equals strings; @else handles it [OK]null equals a string@else runs when no conditions matchnull to output literallyPass the test and this pattern moves unknown