Extending in Sass helps you reuse styles without rewriting them. It keeps your code shorter and easier to manage.
0
0
Why extending reduces duplication in SASS
Introduction
When multiple elements share the same styles and you want to avoid repeating those styles.
When you want to keep your CSS clean and avoid copying and pasting code.
When you want to update a style in one place and have it apply everywhere.
When you want to organize your styles better by grouping common rules.
When you want to reduce the size of your final CSS file by avoiding duplicate code.
Syntax
SASS
%placeholder { property: value; }
.selector { @extend %placeholder; }Use %placeholder selectors to define reusable styles that don't output CSS on their own.
The @extend directive copies styles from the placeholder into the selector.
Examples
This example creates a base button style and extends it in a primary button.
SASS
%button-base {
padding: 1rem;
border-radius: 0.5rem;
font-weight: bold;
}
.btn-primary {
@extend %button-base;
background-color: blue;
color: white;
}Both
.title and .subtitle share the same text style but have different weights and colors.SASS
%text-style {
font-family: Arial, sans-serif;
font-size: 1.2rem;
}
.title {
@extend %text-style;
font-weight: 700;
}
.subtitle {
@extend %text-style;
font-weight: 400;
color: gray;
}Sample Program
This Sass code defines a base card style and extends it for primary and secondary cards. Both cards share padding, border-radius, and shadow, but have different borders and background colors.
SASS
@use 'sass:color'; %card-base { padding: 1rem; border-radius: 0.75rem; box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1); background-color: white; } .card-primary { @extend %card-base; border: 2px solid blue; } .card-secondary { @extend %card-base; border: 2px solid gray; background-color: color.scale(white, $lightness: -10%); } /* HTML example: <div class="card-primary">Primary Card</div> <div class="card-secondary">Secondary Card</div> */
OutputSuccess
Important Notes
Extending copies styles without repeating code, making maintenance easier.
Use placeholders (%) to avoid generating extra CSS selectors.
Be careful: extending too many selectors can create complex CSS output.
Summary
Extending helps reuse styles and reduces repeated code.
Use @extend with placeholders (%) for clean, maintainable Sass.
It keeps your CSS smaller and easier to update.