Sass/SCSS Inheritance Tutorial
In this Sass/SCSS tutorial we learn how to inherit properties from one selector in another with the @extend rule.
What is Inheritance
Sass allows us to inherit properties from other selectors to reduce the amount of code we have to type and/or combining we have to do.
As an example, let’s consider that we have two buttons. They look exactly the same except for the font and background colors.
We can define a basic button style, then let each of the two buttons inherit all the properties from it and add their own custom ones.
Inheriting properties with @extend
To inherit a property from another selector, we use the @extend rule, followed by the name of the selector we want to inherit from.
selector-1 {
s1-property: value;
}
selector-2 {
@extend selector-1;
s2-property: value;
}
We don’t want the properties to be repeated in selector-2 , that just takes up unnecessary space and makes the final CSS file bigger than it needs to be.
So the compiler won’t copy the properties from selector-1 to selector-2 .
Instead, it defines both selectors with all of selector-1 ’s properties and then defines selector-2 with its extra properties.
selector-1, selector-2 {
s1-property: value;
}
selector-2 {
s2-property: value;
}
Let’s see the button example we were talking about earlier.
.btn {
margin: 0 1rem;
padding: 1rem 1.5rem;
border: none;
}
.btn-submit {
@extend .btn;
color: #fff;
background: #000;
}
.btn-disabled {
@extend .btn;
color: #999;
background: #dedede;
}
If we look at the compiled CSS we can see that .btn , .btn-submit and .btn-disabled were defined with .btn ’s properties.
Then .btn-submit and .btn-disabled were again defined with their own custom font and background colors.
.btn, .btn-disabled, .btn-submit {
margin: 0 1rem;
padding: 1rem 1.5rem;
border: none;
}
.btn-submit {
color: #fff;
background: #000;
}
.btn-disabled {
color: #999;
background: #dedede;
}
The compiler has done all the combining for us.
But why is this helpful?
Well, we don’t have to specify both .btn and .btn-submit in our HTML element, we only specify .btn-submit . It’s less code for us to write.
Summary: Points to remember
- We can inherit properties from one selector to another.
- To inherit a property we use the @extend rule followed by the name of the property we want to inherit from.
- Properties aren’t copied into the inheriting selector, they are combined with the inheriting selector.