Introduction to Sass Extend
Sass @extend
Sass @extend is a way to inherit styles from another class or placeholder selector. When you use @extend, you can avoid duplicating styles and keep your code DRY (Don't Repeat Yourself).
To use @extend, you first define a class or placeholder selector that you want to inherit styles from, and then you use @extend to inherit those styles.
As an example:
// Define a base button style
.btn {
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
background-color: #fff;
}
// Define a special button style that inherits from the base button style
.btn-special {
@extend .btn;
color: #fff;
background-color: #f00;
}
In this example
- The
.btn-specialclass inherits all the styles from the.btnclass, including the padding, border-radius, border, and background-color. - The
@extenddirective is used to inherit these styles.
You can also use @extend with placeholder selectors, which are defined using the % symbol instead of the . symbol.
As an example:
// Define a placeholder selector for button styles
%btn {
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
background-color: #fff;
}
// Define a special button style that inherits from the button placeholder
.btn-special {
@extend %btn;
color: #fff;
background-color: #f00;
}
In this example:
- The
%btnplaceholder selector is defined with the same styles as the.btnclass. - The
.btn-specialclass then inherits these styles using@extend %btn.
When you use @extend, Sass generates CSS that combines the styles from both selectors. This can result in more efficient CSS, as it avoids duplicating styles.