0
0
SASSmarkup~8 mins

Generating utility classes with loops in SASS - Performance & Optimization

Choose your learning style9 modes available
Performance: Generating utility classes with loops
MEDIUM IMPACT
This affects CSS file size and browser style calculation time, impacting page load and rendering speed.
Creating multiple margin utility classes for spacing
SASS
@for $i from 1 through 10 {
  .m-#{$i} {
    margin: #{$i}rem;
  }
}
Generates fewer classes with rem units for better scalability and smaller CSS size.
📈 Performance GainSaves ~90% CSS size; reduces style calculation time and improves LCP.
Creating multiple margin utility classes for spacing
SASS
@for $i from 1 through 1000 {
  .m-#{$i} {
    margin: #{$i}px;
  }
}
Generates 1000 classes, bloating CSS and increasing style calculation time.
📉 Performance CostAdds ~50-100kb to CSS bundle; increases style calculation time significantly.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Generating 1000 utility classes with px unitsNo extra DOM nodesNo reflows triggered by CSS aloneHigh paint cost due to large CSS and style calculation[X] Bad
Generating 10 utility classes with rem unitsNo extra DOM nodesNo reflows triggered by CSS aloneLow paint cost due to small CSS and fast style calculation[OK] Good
Rendering Pipeline
The generated CSS classes are parsed during style calculation. Larger CSS files increase style calculation and layout time, delaying paint.
Style Calculation
Layout
Paint
⚠️ BottleneckStyle Calculation
Core Web Vital Affected
LCP
This affects CSS file size and browser style calculation time, impacting page load and rendering speed.
Optimization Tips
1Limit the number of utility classes generated in loops to reduce CSS size.
2Use scalable units like rem instead of px for better performance and responsiveness.
3Avoid generating classes for every single pixel value; use meaningful steps.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a main performance risk when generating many utility classes with loops in Sass?
ALarge CSS file size increasing style calculation time
BAdding many DOM nodes dynamically
CIncreasing JavaScript bundle size
DTriggering multiple reflows on each class
DevTools: Performance
How to check: Record a performance profile while loading the page; look at the 'Style Recalculation' and 'Layout' times.
What to look for: Long style recalculation times or large CSS files indicate performance issues with generated utility classes.