0
0
CSSmarkup~8 mins

Declaring variables in CSS - Performance & Optimization

Choose your learning style9 modes available
Performance: Declaring variables
LOW IMPACT
Declaring CSS variables affects how styles are computed and reused, impacting style calculation and paint performance.
Reusing colors or sizes multiple times in CSS
CSS
:root { --primary-color: #3498db; }
.button { color: var(--primary-color); background-color: var(--primary-color); border-color: var(--primary-color); }
Declaring a variable once and reusing it reduces repeated style calculations and improves maintainability.
📈 Performance GainSingle style calculation for the variable value reused multiple times
Reusing colors or sizes multiple times in CSS
CSS
:root { }
.button { color: #3498db; background-color: #3498db; border-color: #3498db; }
Repeating the same color value multiple times causes the browser to recalculate styles separately for each property.
📉 Performance CostTriggers multiple style recalculations for repeated values
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Repeating literal valuesMinimalMinimalHigher due to repeated style calculations[X] Bad
Using CSS variablesMinimalMinimalLower due to reuse of computed values[OK] Good
Rendering Pipeline
CSS variables are resolved during the Style Calculation stage. Using variables reduces repeated parsing and recalculation of identical values, improving efficiency.
Style Calculation
Paint
⚠️ BottleneckStyle Calculation when many repeated values are declared inline
Optimization Tips
1Declare CSS variables once at a high level like :root for reuse.
2Use variables to avoid repeating identical style values multiple times.
3Reusing variables reduces style calculation time but does not affect layout or paint directly.
Performance Quiz - 3 Questions
Test your performance knowledge
How do CSS variables affect style calculation performance?
AThey reduce repeated style calculations by reusing values
BThey increase the number of reflows
CThey block rendering until variables are loaded
DThey cause more paint operations
DevTools: Performance
How to check: Record a performance profile while loading the page and inspect the Style Calculation phase to see if repeated values cause extra work.
What to look for: Look for reduced time in Style Calculation when using CSS variables compared to repeated literals.