Another great feature of Sass is inheritance. We implement this using the @extend
directive.
Inheritance is a feature of SASS that allows multiple classes to share a common set of properties with one another.
An Example
Some typical CSS code for styling a button:
.button {
background-color: #0000FF; // Blue
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 1.5rem;
}
If we happen to have a number of buttons on our website, all of which are styled in a similar manner, we would have a good case for inheritance!
We would implement a secondary button via inheritance like so:
.button-secondary {
@extend .button;
background-color: #4CAF50; // Green
}
Our .button-secondary
class will take on all of the properties and values set the .button class
, with the exception of background-color
which weâve decided to set to green.
The use of inheritance helps us to keep our code neat, clean and focused on constructing reusable components.
Up next in this series, weâll take a look at the &
operator.
Related Posts:
A little about me..
Hey, Iâm Tim! đ
Iâm a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out my Complete Guide to Freelancing if you'd like to find out more.
While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.
Thanks for reading! đ