In this tutorial, we'll explore how to use the @extend feature in SASS (Syntactically Awesome Stylesheets)/SCSS (Sassy CSS) to avoid duplicating code. SASS is a scripting language that is interpreted into CSS, and it brings several useful features to the table that standard CSS lacks.
The @extend directive allows one selector to inherit the styles of another selector, helping you to keep your code DRY (Don't Repeat Yourself) and easier to maintain.
@extend directive in SASS/SCSS.@extend to avoid code duplication.The @extend directive in SASS enables a selector to inherit the styles of another selector. It's like creating a relationship between two selectors where one selector inherits the characteristics of the other.
Let's say we have a CSS class .btn with some styles. If we want another class, say .btn-primary, to have the same styles plus some additional styles, we would use the @extend directive like this:
.btn {
padding: 10px;
border-radius: 3px;
font-size: 16px;
}
.btn-primary {
@extend .btn;
background-color: blue;
color: white;
}
In the above example, .btn-primary will have the same padding, border-radius, and font-size as .btn, plus its own background-color and color.
Let's dive into some more practical examples.
.error {
border: 1px solid red;
color: red;
}
.seriousError {
@extend .error;
background-color: #fdd;
}
In the above code, .seriousError will inherit the styles of .error and add its own background-color.
You can extend multiple classes as well. Consider the following example:
.warning {
border: 1px solid yellow;
color: yellow;
}
.error {
@extend .warning;
border-color: red;
color: red;
}
.seriousError {
@extend .error;
background-color: #fdd;
}
In this example, .seriousError inherits the styles of .error (which itself extends .warning), and adds its own background-color.
In this tutorial, we've learned how to use the @extend directive in SASS/SCSS to avoid duplicating code by allowing one selector to inherit the styles of another selector. This helps in maintaining cleaner and DRY code.
Create a .container class with some styles and then create .container-fluid class that extends .container and adds its own styles.
Create a .card class with some styles. From that, extend a .card-primary and .card-secondary class, each adding their own unique styles.
Create a .btn class and extend it to .btn-primary, .btn-secondary, and .btn-danger, each having their own unique styles.
Hint: Make use of the @extend directive to inherit styles from the base class.