Extends & Inheritance in SCSS
What is @extend in SCSS?
The @extend directive in SCSS allows you to share styles from one selector to another. This is a powerful feature for code reuse and creating DRY (Don't Repeat Yourself) stylesheets.
Basic Syntax
.button {
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.primary-button {
@extend .button;
background-color: #3498db;
color: white;
}
.secondary-button {
@extend .button;
background-color: #2ecc71;
color: white;
}
Compiles to:
.button, .primary-button, .secondary-button {
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.primary-button {
background-color: #3498db;
color: white;
}
.secondary-button {
background-color: #2ecc71;
color: white;
}
Placeholder Selectors (%)
Placeholder selectors (also called "silent" classes) begin with a % symbol and are only compiled into CSS when they're extended with @extend. They are ideal for styles that are only meant to be extended.
// Placeholder selector (not compiled directly)
%button-base {
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
}
.primary-button {
@extend %button-base;
background-color: #3498db;
color: white;
&:hover {
background-color: darken(#3498db, 10%);
}
}
.secondary-button {
@extend %button-base;
background-color: #2ecc71;
color: white;
&:hover {
background-color: darken(#2ecc71, 10%);
}
}
Compiles to:
.primary-button, .secondary-button {
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
}
.primary-button {
background-color: #3498db;
color: white;
}
.primary-button:hover {
background-color: #2980b9;
}
.secondary-button {
background-color: #2ecc71;
color: white;
}
.secondary-button:hover {
background-color: #25a25a;
}
Note: Notice that the placeholder selector %button-base doesn't appear in the compiled CSS. It only serves as a "template" for other selectors.