Using @extend in SCSS allows you to share styles between selectors without duplicating code. It works by inheriting the styles of one selector into another, helping you maintain a cleaner and more efficient stylesheet. This is especially useful for applying common styles like buttons, alerts, or utility classes across multiple elements. Unlike mixins, @extend merges selectors in the compiled CSS, which can reduce file size. Overall, it helps promote reusability and keeps your SCSS code more organized.
What is @extend in SCSS?
@extend allows one selector to inherit styles from another. It helps you reuse existing styles without duplicating code.
Example:
.button {
padding: 10px 20px;
border-radius: 5px;
}
.primary-btn {
@extend .button;
background: blue;
color: white;
}
Sharing Common Styles
You can define a base class and extend it across multiple components to maintain consistency.
Example:
.card {
padding: 20px;
border: 1px solid #ddd;
}
.product-card {
@extend .card;
}
.profile-card {
@extend .card;
}
Using Placeholder Selectors (%)
Instead of extending real classes, you can use placeholder selectors (%) which won’t be compiled into CSS unless extended.
Example:
%box {
padding: 15px;
border-radius: 8px;
}
.alert {
@extend %box;
background: red;
}
.success {
@extend %box;
background: green;
}
Extending Multiple Selectors
You can extend multiple styles into one class for combining behaviors.
Example:
.btn {
padding: 10px;
}
.rounded {
border-radius: 20px;
}
.btn-rounded {
@extend .btn;
@extend .rounded;
}
When to Use @extend vs Mixins
Use @extend when styles are identical and shared. Use mixins when you need flexibility, parameters, or dynamic values.
Example:
// Better for reuse (no duplication)
.alert {
@extend %box;
}
// Better for dynamic styles
@mixin button($color) {
background: $color;
}
.btn-blue {
@include button(blue);
}



