Performance: Extend limitations and gotchas
Using @extend in Sass affects CSS generation size and browser rendering performance by increasing selector complexity and causing style recalculations.
@mixin button-styles { padding: 1rem; background: blue; } .button { @include button-styles; } .card { @include button-styles; color: white; }
.button { padding: 1rem; background: blue; } .card { @extend .button; color: white; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| @extend with many selectors | No extra DOM nodes | Triggers multiple reflows if styles change | High paint cost due to complex styles | [X] Bad |
| Mixin for style reuse | No extra DOM nodes | Single reflow on style change | Lower paint cost with simpler styles | [OK] Good |
@extend in Sass?@extend does@extend reuses styles by merging selectors in the final CSS output.@extend merges selectors = A [OK]@extend merges selectors, not duplicates styles [OK]@extend duplicates styles@extend only works with IDs@extend cannot be nested%button-base inside a class .primary-button?% and must be referenced exactly with @extend %name.@extend %button-base correctly.@extend %placeholder syntax = C [OK].alert { color: red; }
.error { @extend .alert; font-weight: bold; }@extend merges selectors.error selector extends .alert, so both selectors share the color: red; style..alert, .error has color: red;, and .error has its own font-weight: bold;.@extend merges selectors.btn { color: blue; }
.special-btn { @extend .btn; background: yellow; }
.btn-primary { @extend .btn; }.btn-primary?@extend merges selectors.btn are merged into one combined selector group in the output CSS..special-btn and .btn-primary extend .btn, their selectors get merged, causing combined selectors.@extend merges all selectors that extend .btn into one group -> Option C@extend merges selectors = B [OK]@extend duplicates styles@extend only works with placeholders@extend cannot be used with classes@extend. Which approach is best?% and do not output CSS unless extended.@extend@extend to media queries doesn't solve unwanted output.%base-style) and extend them -> Option D@extend to avoid extra CSS [OK]@extend inside media queriesPass the test and this pattern moves unknown