0
0
SASSmarkup~8 mins

@if conditional logic in SASS - Performance & Optimization

Choose your learning style9 modes available
Performance: @if conditional logic
LOW IMPACT
This affects CSS compilation time and the size of the generated CSS file, impacting initial page load speed.
Generating CSS styles conditionally based on variables
SASS
@mixin button-style($type) {
  color: black;
  background: white;
  @if $type == 'primary' {
    background: blue;
    color: white;
  } @else if $type == 'secondary' {
    background: gray;
  }
}

.button-primary {
  @include button-style('primary');
}

.button-secondary {
  @include button-style('secondary');
}
Generates only the needed CSS for each button type, avoiding duplication and reducing file size.
📈 Performance Gainreduces CSS file size, improving LCP and load speed
Generating CSS styles conditionally based on variables
SASS
@mixin button-style($type) {
  color: black;
  background: white;
  @if $type == 'primary' {
    background: blue;
    color: white;
  }
  @if $type == 'secondary' {
    background: gray;
  }
}

.button-primary {
  @include button-style('primary');
}

.button-secondary {
  @include button-style('secondary');
}
Including multiple conditional styles for all types causes duplicated CSS rules and larger file size.
📉 Performance Costadds unnecessary CSS bytes, increasing CSS file size and slowing LCP
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Using multiple @if blocks generating duplicated CSSN/AN/AHigher due to larger CSS[X] Bad
Using @if with else-if to generate minimal CSSN/AN/ALower due to smaller CSS[OK] Good
Rendering Pipeline
Sass @if conditions are evaluated at compile time, affecting the CSS output size which impacts the browser's CSS parsing and rendering speed.
CSS Parsing
Style Calculation
Layout
⚠️ 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, impacting initial page load speed.
Optimization Tips
1Use @if to generate only the CSS you need to keep file size small.
2Avoid multiple separate @if blocks that create duplicated CSS rules.
3Smaller CSS files improve page load speed and LCP.
Performance Quiz - 3 Questions
Test your performance knowledge
How does using @if conditional logic in Sass affect page performance?
AIt increases DOM nodes in the browser.
BIt reduces CSS file size by generating only needed styles.
CIt causes more JavaScript execution on the client.
DIt delays image loading on the page.
DevTools: Network
How to check: Open DevTools, go to Network tab, reload page, filter by CSS files, and check CSS file size.
What to look for: Smaller CSS file size indicates better use of conditional logic reducing unnecessary styles.