Explain what is a @extend directive used for in Sass?
Explain what is a @extend directive used for in Sass?
The @extend
directive in Sass is a powerful feature used for sharing a set of CSS properties from one selector to another. This directive is particularly useful for maintaining clean and DRY (Don't Repeat Yourself) code in stylesheets. When you use @extend
, you allow one selector to inherit the styles of another selector, effectively grouping selectors together to share common styling rules without duplicating code[1][2][3][4][5][8].
The @extend
directive works by combining selectors that share common styles into a single CSS rule set. This not only helps in reducing the repetition of styles but also keeps the stylesheet organized and easier to maintain. For example, if you have multiple button styles that share basic properties but differ slightly in color or size, you can define a base .button
style and use @extend
to inherit these base styles into more specific button types[8].
Consider a scenario where you have a basic button style and two other buttons that only differ in background color:
.button-basic {
border: none;
padding: 15px 30px;
text-align: center;
font-size: 16px;
cursor: pointer;
}
.button-report {
@extend .button-basic;
background-color: red;
}
.button-submit {
@extend .button-basic;
background-color: green;
}
After compilation, the CSS output groups the shared properties, reducing redundancy:
.button-basic, .button-report, .button-submit {
border: ...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào