SCSS @extend directive explained
SCSS @extend Directive Detailed Explanation
When using SCSS (Sassy
What is the @extend Directive?
The @extend directive is a way to reuse styles in SCSS, allowing one selector to inherit the styles of another. Using the @extend directive, we can avoid duplicating similar style code and improve style maintainability.
Basic Syntax of the @extend Directive
The basic syntax of the @extend directive is as follows:
%placeholder {
// Style code
}
.selector {
@extend %placeholder;
}
In the above syntax, “%placeholder” is a placeholder that represents a set of style codes. Using “@extend %placeholder;” in the style of “selector” will inherit the styles in “%placeholder”.
Example of Using the @extend Directive
The following example demonstrates the application of the @extend directive.
%button {
padding: 10px 20px;
background-color: #4285f4;
color: #fff;
border-radius: 5px;
}
.button-primary {
@extend %button;
}
.button-secondary {
@extend %button;
background-color: #34a853;
}
.button-danger {
@extend %button;
background-color: #ea4335;
}
.button-warning {
@extend %button;
background-color: #fbbc05;
}
In the example above, “%button” is defined as a placeholder containing common button styles. Then, different button styles are defined. The @extend directive inherits the styles from “%button” and can override some of them.
Notes on the @extend Directive
When using the @extend directive, be aware of several things to avoid potential problems:
- Avoid overuse of the @extend directive, which can lead to cluttered style code and make maintenance difficult.
- Inherited styles will be merged into the inheritor’s styles, potentially causing style redundancy. Use with caution.
- Avoid cross-level @extend inheritance, which can easily lead to uncontrolled styles.
Summary
Through this article, we’ve learned the role and basic usage of the @extend directive in SCSS. It can help us reuse styles and improve development efficiency. In real-world development, appropriate use of the @extend directive can make CSS styles cleaner and easier to maintain.