In this tutorial, we will be focusing on how to use the @extend directive in SASS/SCSS for creating efficient stylesheets by inheriting styles from another selector. This is a powerful feature that can help you avoid code repetition and make your stylesheets more maintainable and readable.
By the end of this tutorial, you should be able to:
- Understand how the @extend directive works
- Use @extend to inherit styles from other selectors
- Apply best practices when using @extend
Prerequisites: Basic knowledge of CSS and understanding of SASS/SCSS.
The @extend directive in SASS/SCSS is used to inherit the styles of one selector from another. This is similar to how classes can inherit properties and methods from another class in object-oriented programming.
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
@extend .error;
border-width: 3px;
}
In this example, .seriousError
will inherit the styles from .error
and then add its own styles. The generated CSS will look like this:
.error, .seriousError {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
border-width: 3px;
}
%button {
display: inline-block;
padding: 5px 10px;
border-radius: 3px;
text-align: center;
}
.primary-button {
@extend %button;
background-color: #007bff;
color: white;
}
.secondary-button {
@extend %button;
background-color: #6c757d;
color: white;
}
In this example, .primary-button
and .secondary-button
both extend the %button
placeholder selector. The generated CSS will look like this:
.primary-button, .secondary-button {
display: inline-block;
padding: 5px 10px;
border-radius: 3px;
text-align: center;
}
.primary-button {
background-color: #007bff;
color: white;
}
.secondary-button {
background-color: #6c757d;
color: white;
}
In this tutorial, we learned how to use the @extend directive in SASS/SCSS to inherit styles from another selector. We have seen how @extend can make your stylesheets more efficient and maintainable, and we've also covered some best practices when using @extend.
Next steps for learning include exploring other SASS/SCSS features such as mixins, variables, and functions.
Additional resources:
- SASS/SCSS documentation
Create a basic stylesheet with a few selectors, and try using @extend to inherit styles. Experiment with different combinations of selectors and properties.
Create a stylesheet using @extend with placeholder selectors. Try to extend multiple placeholder selectors in one selector.
Create a complex stylesheet with nested selectors, and use @extend to inherit styles across different levels of nesting.
Solutions and explanations for these exercises will depend on your creativity, but remember the best practices covered in this tutorial. For further practice, consider refactoring an existing stylesheet to use @extend where possible.