SCSS Extend
SCSS Extend

SCSS (Sassy @extend directive allows style rules to “inherit” the style rules of another selector. By using @extend, you can reduce duplicate style code and improve code maintainability and readability.
Grammar
The basic syntax of
@extend is as follows:
.selector {
property: value;
@extend .another-selector;
}
In the above code, the styles in .selector will inherit the styles in .another-selector.
Usage Scenarios
1. Inheriting Common Styles
A common usage scenario is to extract the same styles from multiple selectors, define them as a common style, and then inherit the common styles through @extend.
%common-style {
background-color: #f8f8f8;
color: #333;
}
.header {
@extend %common-style;
}
.footer {
@extend %common-style;
}
In the above code, both the .header and .footer selectors inherit the common styles defined in %common-style.
2. Inheriting Media Queries
@extend can also be used to inherit media queries. For example:
%mobile {
@media (max-width: 768px) {
@content;
}
}
.element {
@extend %mobile {
color: blue;
}
}
In the above code, the .element selector will apply the blue color to screen widths less than or equal to 768px.
Notes
1. Inherited styles must be defined after the inherited styles
In SCSS, the @extend directive must be defined after the inherited style rules. Otherwise, a compilation error will occur.
.error {
color: red;
}
.success{
@extend .error;
color: green; // This will result in a compilation error.
}
2. Can only inherit from one selector
In SCSS, @extend is one-way: a selector can only inherit the styles of one selector.
3. V.S. Mixin
While both @extend and mixin can reuse styles, there are some differences between them. @extend directly merges the inherited styles into the current style, while mixin inserts the styles from the mixin into the place where the mixin is called.
Example
Here is an example code using @extend:
%button-style {
padding: 10px 20px;
border: 1px solid #333;
background-color: #f8f8f8;
color: #333;
text-align: center;
cursor: pointer;
}
.button {
@extend %button-style;
}
.button-primary {
@extend %button-style;
background-color: #007bff;
color: white;
}
.button-secondary {
@extend %button-style;
background-color: #28a745;
color: white;
}
.button-disabled {
@extend %button-style;
background-color: #ccc;
color: #666;
cursor: not-allowed;
}
In the example code above, the .button, .button-primary, .button-secondary, and .button-disabled selectors all inherit the common styles defined in %button-style.
Summary
@extend is a very convenient feature in SCSS that can help reduce style duplication and improve code maintainability and readability. However, there are some caveats to avoid errors when using it. In real-world projects, proper use of @extend can make your style code more concise and efficient.