Performance: Grid column generator with loops
This affects the CSS generation size and browser rendering performance by controlling how many grid column classes are created and used.
Jump into concepts and practice - no test required
@for $i from 1 through 12 { .col-#{$i} { grid-column: span #{$i}; } }
@for $i from 1 through 100 { .col-#{$i} { grid-column: span #{$i}; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Generating 100 grid column classes | No extra DOM nodes | No extra reflows | Higher paint cost due to larger CSS | [X] Bad |
| Generating 12 grid column classes | No extra DOM nodes | No extra reflows | Lower paint cost with smaller CSS | [OK] Good |
@for loop in SASS help you do when creating grid columns?@for in SASS@for loop repeats code blocks a set number of times, useful for generating CSS classes.@for with grid columns@for, you can create many classes like .col-1, .col-2, etc., each with different widths.@for loop = Generate CSS classes [OK]@for as a shortcut to write many classes fast [OK]@for writes HTML elements@for syntax in SASS@for $var from start through end to include the end number.@for $i from 1 through 4, which is correct. Options A, B, and C use invalid keywords or syntax.@for syntax = @for $i from 1 through 4 { .col-#{$i} { width: 25% * $i; } } [OK]@for $i from 1 through 3 {
.col-#{$i} {
grid-column: span $i;
}
}grid-column: span $i;, so .col-1 spans 1 column, .col-2 spans 2, and .col-3 spans 3.@for $i from 1 to 4 {
.col-#{$i} {
width: 100% / $i;
}
}@for $i from 1 to 4, which excludes the end number 4. Use through to include it..col-2, .col-4, and .col-6 with widths as fractions of 6 columns?@for loops do not support 'step' directly, so use @if $i % 2 == 0 to filter even numbers.@if $i % 2 == 0 correctly. @for $i from 1 through 6 {
@if $i / 2 == 0 {
.col-#{$i} {
width: (100% / 6) * $i;
}
}
} uses division instead of modulo, which is wrong. @each $i from (2, 4, 6) {
.col-#{$i} {
width: (100% / 6) * $i;
}
} uses invalid syntax ('from' instead of 'in' for @each). @for $i from 2 to 6 step 2 {
.col-#{$i} {
width: (100% / 6) * $i;
}
} uses invalid 'step' syntax.