Performance: Recursive mixins
This affects CSS compilation time and the size of the generated CSS, impacting page load speed and rendering performance.
Jump into concepts and practice - no test required
@mixin recursive-good($n) { @for $i from 1 through $n { .level-#{$i} { color: red; } } } @include recursive-good(10);
@mixin recursive-bad($n) { @if $n > 0 { .level-#{$n} { color: red; @include recursive-bad($n - 1); } } } @include recursive-bad(10);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Recursive mixin with deep nesting | N/A (CSS only) | N/A | High due to complex selectors | [X] Bad |
| Loop-based mixin generating flat CSS | N/A (CSS only) | N/A | Low due to simple selectors | [OK] Good |
sass?sass?@if $n > 0 to stop recursion when $n reaches 0.$n - 1, moving towards stop condition..box after compilation?@mixin colorLayers($n) {
@if $n > 0 {
color: lighten(blue, $n * 10%);
@include colorLayers($n - 1);
}
}
.box {
@include colorLayers(2);
}color: lighten(blue, $n * 10%). So first lighten by 20%, then by 10%.@mixin borderLayers($count) {
border: 1px solid black;
@include borderLayers($count - 1);
}@if $count > 0 before recursive call stops recursion when count reaches 0.@if $count > 0 before recursive call -> Option A@if $n > 0 to stop recursion and increments blur by 2 each call.$n - 1 and increasing blur, layering shadows correctly 3 times.