The goal of this tutorial is to help you understand the limitations of using the @extend directive in SASS/SCSS. You will learn about the potential issues that can arise when using @extend and how to use it more effectively.
Prerequisites:
Basic knowledge of SASS/SCSS and CSS is required.
The @extend directive in SASS/SCSS allows one selector to inherit the styles of another selector. It's a powerful feature, but it has its limitations and potential issues.
The primary limitation is that @extend can only extend simple selectors. This means it cannot extend complex selectors or selectors with pseudo-classes.
Another limitation is that using @extend can lead to bloated CSS output if not used carefully. This is because every time you use @extend, SASS/SCSS generates all the possible combinations of selectors.
Best Practices and Tips:
1. Use @extend sparingly to avoid bloated CSS output.
2. Instead of @extend, consider using mixins or placeholder selectors where appropriate.
3. Always review your compiled CSS to ensure it is as efficient as possible.
Example 1: Simple @extend
.error {
border: 1px solid red;
}
.warning {
@extend .error;
background-color: yellow;
}
In the above example, .warning
extends .error
, meaning it inherits the border style from .error
. The compiled CSS will be:
.error, .warning {
border: 1px solid red;
}
.warning {
background-color: yellow;
}
Example 2: Limitation of @extend
.error:hover {
border: 1px solid red;
}
.warning {
@extend .error:hover;
background-color: yellow;
}
In the second example, we try to @extend a pseudo-class, which is not allowed. This will throw an error in SASS/SCSS.
In this tutorial, you've learned about the limitations of @extend in SASS/SCSS. You've also seen how to use @extend correctly and some best practices to follow.
Next, consider exploring other features of SASS/SCSS such as mixins and placeholder selectors.
Additional Resources:
SASS/SCSS Documentation
Exercise 1:
Write SCSS code to style a .success
class, that extends the styles of a .message
class.
Solution:
.message {
border: 1px solid green;
color: green;
}
.success {
@extend .message;
background-color: lightgreen;
}
Exercise 2:
Given the following SCSS, what will be the compiled CSS output?
.btn {
padding: 10px;
border-radius: 5px;
}
.btn-primary {
@extend .btn;
background-color: blue;
color: white;
}
Solution:
.btn, .btn-primary {
padding: 10px;
border-radius: 5px;
}
.btn-primary {
background-color: blue;
color: white;
}
Keep practicing with different scenarios to get more comfortable with @extend and its limitations.