Extending and mixing help reuse styles in Sass so you don't repeat yourself. They make your CSS cleaner and easier to manage.
Extending vs mixing comparison in SASS
@extend .selector-to-extend; @mixin mixin-name { property: value; } @include mixin-name;
@extend copies styles from one selector to another by merging selectors in the CSS output.
@mixin defines reusable style blocks, and @include inserts those styles where needed.
@extend to share styles from .button to .primary-button..button { background: blue; color: white; } .primary-button { @extend .button; font-weight: bold; }
@mixin to define styles and @include to add them to .primary-button.@mixin button-styles { background: blue; color: white; } .primary-button { @include button-styles; font-weight: bold; }
@extend merges selectors, so both .alert and .error share styles..alert { border: 1px solid red; padding: 1rem; } .error { @extend .alert; background: pink; }
@mixin copies styles directly into .error, keeping selectors separate.@mixin alert-styles { border: 1px solid red; padding: 1rem; } .error { @include alert-styles; background: pink; }
This example shows two ways to reuse styles. The blue buttons share styles using @extend, so their CSS selectors are combined. The alert and error boxes show how @mixin copies styles separately, so the error box has its own background color added.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Extending vs Mixing Example</title> <style> /* Compiled CSS from Sass example */ .button, .primary-button { background: blue; color: white; } .primary-button { font-weight: bold; } .alert, .error { border: 1px solid red; padding: 1rem; } .error { background: pink; } </style> </head> <body> <button class="button">Normal Button</button> <button class="primary-button">Primary Button</button> <div class="alert">Alert Box</div> <div class="error">Error Box</div> </body> </html>
@extend merges selectors in the final CSS, which can reduce file size but may cause unexpected style inheritance.
@mixin copies styles wherever included, which can increase CSS size but keeps selectors separate and predictable.
Use @extend for simple shared styles and @mixin when you need more control or parameters.
@extend shares styles by combining selectors in the CSS output.
@mixin copies style blocks into selectors where included.
Choose @extend for smaller CSS and @mixin for flexible, reusable styles.