Performance: @each loop over maps
This affects CSS generation time and the final CSS file size, impacting page load speed and render time.
$colors: (red: #f00, green: #0f0, blue: #00f); @each $name, $hex in $colors { .text-#{$name} { color: $hex; } .bg-#{$name} { background-color: $hex; } }
@each $color in (red, green, blue) { .text-#{$color} { color: $color; } } @each $color in (red, green, blue) { .bg-#{$color} { background-color: $color; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Separate @each loops over lists | N/A (build time) | N/A | Larger CSS size delays style application | [X] Bad |
| Single @each loop over map | N/A (build time) | N/A | Smaller CSS size loads faster | [OK] Good |
@each loop do when used with a map in Sass?@each with maps@each loop iterates over each key-value pair in a map.@each loops over map pairs = repeats styles [OK]@each repeats code for each map pair [OK]@each deletes map entries$colors with @each in Sass?@each syntax for mapsin, then the map name.@each $key, $value in $colors. Others have wrong order or missing comma.in + map name [OK]$themes: (light: #fff, dark: #000); @each $name, $color in $themes { .#{$name}-theme { background: $color; } }What CSS will this generate?light and dark with colors #fff and #000..#{$name}-theme producing .light-theme and .dark-theme. The background uses the color value.$sizes: (small: 1rem, medium: 2rem); @each $size in $sizes { .btn-#{$size} { font-size: $size; } }@each loop variables$size instead of $key, $value, so it cannot access both parts of the map.@each loops [OK]@each loops [OK]$shadows: (none: 0 0 0 transparent, light: 0 1px 3px rgba(0,0,0,0.12), heavy: 0 4px 6px rgba(0,0,0,0.3));
@each loop that creates classes .shadow-none, .shadow-light, and .shadow-heavy with the correct box-shadow property. Which code snippet is correct?@each $key, $value in $map, so $name is key and $shadow is value.$name, and the property uses the value $shadow.Pass the test and this pattern moves unknown