0
0
SASSmarkup~8 mins

@else and @else if branches in SASS - Performance & Optimization

Choose your learning style9 modes available
Performance: @else and @else if branches
LOW IMPACT
This affects CSS compilation time and the size of the generated CSS file, which impacts page load speed.
Writing conditional styles in Sass to avoid duplicate CSS rules
SASS
@if $font-scale >= 1.5 {
  h1 {
    font-size: 3rem;
  }
} @else if $font-scale >= 1.0 {
  h1 {
    font-size: 2rem;
  }
}
Using @else if chains stops evaluation once a condition matches, reducing generated CSS and compile work.
📈 Performance Gainreduces CSS file size and compilation time
Writing conditional styles in Sass to avoid duplicate CSS rules
SASS
@if $font-scale >= 1.5 {
  h1 {
    font-size: 3rem;
  }
}
@if $font-scale >= 1.0 {
  h1 {
    font-size: 2rem;
  }
}
Using separate @if statements causes Sass to evaluate all conditions independently, potentially generating redundant CSS.
📉 Performance Costincreases CSS file size and compilation time slightly
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Separate @if statementsN/AN/ALarger CSS file increases parsing time[X] Bad
@if with @else if branchesN/AN/ASmaller CSS file reduces parsing time[OK] Good
Rendering Pipeline
Sass @else and @else if branches affect the CSS generation step before the browser rendering pipeline. Efficient branching reduces CSS size, which speeds up CSS parsing and style calculation in the browser.
CSS Parsing
Style Calculation
⚠️ BottleneckCSS Parsing due to larger CSS files
Core Web Vital Affected
LCP
This affects CSS compilation time and the size of the generated CSS file, which impacts page load speed.
Optimization Tips
1Use @else and @else if to avoid generating duplicate CSS rules.
2Smaller CSS files load and parse faster, improving LCP.
3Avoid multiple separate @if statements when conditions are mutually exclusive.
Performance Quiz - 3 Questions
Test your performance knowledge
How does using @else if instead of separate @if statements in Sass affect CSS performance?
AIt triggers more reflows in the browser
BIt reduces CSS file size and speeds up CSS parsing
CIt increases the number of DOM nodes
DIt has no effect on performance
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by CSS files, and compare file sizes of generated CSS with and without @else if usage.
What to look for: Smaller CSS file size indicates better performance; also check load time for CSS files.