Performance: Spacing scale generation
This affects CSS file size and browser rendering speed by controlling how spacing values are generated and reused.
Jump into concepts and practice - no test required
$base-spacing: 4px; @function spacing($step) { @return $base-spacing * $step; } .element { margin: spacing(1) spacing(2) spacing(3) spacing(4); }
$spacing-1: 4px; $spacing-2: 8px; $spacing-3: 12px; $spacing-4: 16px; $spacing-5: 20px; .element { margin-top: 4px; margin-right: 8px; margin-bottom: 12px; margin-left: 16px; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual spacing values for each element | Low | Multiple reflows if spacing changes | Medium due to many unique styles | [X] Bad |
| Function-generated spacing scale | Low | Single reflow on spacing change | Low due to fewer unique styles | [OK] Good |
$spacing-scale: (1: 0.25rem, 2: 0.5rem, 3: 1rem);
@mixin spacing($size) {
margin: map-get($spacing-scale, $size);
}
.box {
@include spacing(2);
}.box class?@function generate-spacing($steps) {
$scale: ();
@for $i from 1 through $steps {
$scale: map-merge($scale, $i: $i * 0.25rem);
}
@return $scale;
}
$spacing-scale: generate-spacing(3);