Performance: Why advanced mixins solve complex problems
This affects CSS generation size and browser rendering speed by reducing repetitive code and complex selector duplication.
Jump into concepts and practice - no test required
@mixin button-style($bg, $hover-bg) { background-color: $bg; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); &:hover { background-color: $hover-bg; } } .button-primary { @include button-style(blue, darkblue); } .button-secondary { @include button-style(gray, darkgray); }
@mixin button-style { background-color: blue; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); &:hover { background-color: darkblue; } } .button-primary { @include button-style; } .button-secondary { background-color: gray; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); &:hover { background-color: darkgray; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual repeated styles | No extra DOM nodes | Multiple reflows if styles change | Higher paint cost due to larger CSS | [X] Bad |
| Advanced parameterized mixins | No extra DOM nodes | Single reflow per style change | Lower paint cost due to smaller CSS | [OK] Good |
@mixin card($bg) { background-color: $bg; padding: 1rem; }
.box { @include card(lightblue); }box in the compiled CSS?card sets background-color to the parameter $bg and padding to 1rem..box includes card(lightblue), so $bg is lightblue.@mixin alert($type) {
@if $type == 'error' { color: red; }
@else if $type == 'success' { color: green; }
}
.msg { @include alert(); }alert requires one parameter $type.@include alert(); without passing $type, causing an error.