Introduction
Extend helps reuse styles in Sass, but it has some limits and tricky parts to know so your styles work well.
@extend selector;@extend inside a CSS rule to copy styles from another selector..link class will get all styles from .button plus its own..button { background: blue; color: white; } .link { @extend .button; text-decoration: underline; }
.error class reuses .alert styles and adds a pink background..alert { border: 1px solid red; padding: 1rem; } .error { @extend .alert; background: pink; }
.card style. Then .highlight and .note reuse it with some changes. The background of .highlight is a darker white, and .note has a dashed border.@use 'sass:color'; .card { border: 2px solid black; padding: 1rem; background: white; } .highlight { @extend .card; background: color.scale(white, $lightness: -20%); } .note { @extend .card; border-style: dashed; }
%placeholder) is safer because they don't output CSS on their own.@extend might not work as expected.@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