Keep your styles DRY with inheritance from Sass
Keeping your CSS files DRY can be a hassle. Often times there are multiple elements that share similar styles and as a project grows and changes you find yourself having to search through dozens, hundreds, or thousands of lines of styles to overwrite previous ones. Sass comes in to help by allowing you to create placeholder classes that enable you to extend those styles to other selectors and in turn help you maintain, grow and keep those styles DRY!
5 Buttons
Lets say we have a simple web page with 5 buttons. They’ll share a some styles like width, height, color, etc. but all their background colors are the same. There’s a couple ways of doing this in our CSS file.
Naïve Approach
The naïve approach would be to create a single class for each button and manually type out each style — Copying the same height, width, color, etc. for each button.
If you’re new to CSS, and think this is tedious, I’d agree. There’s a better and faster way to do this.
Approach 2: Select all the buttons
This time we’ll add the prefix “button-” to the class names to get button-red, button-blue, and so forth. Then we’ll use CSS to select all the styles and add the similar styles at once. We’ll add the background-color individually afterwards.
While this works, I’d argue that we that there is some room for improvement. Lets refactor a little bit.
Approach 3: Refactor into a new class
Next we’ll encapsulate the shared styles into it’s own single class, “button”, to follow the age old programming principle of the Separation of Concerns. Lets not forget to update the class names while we’re at it.
This is probably as good as we can get with plain CSS and I’d say its pretty good.
Approach 4: Adding Sass
If we look at our HTML, we can see that there is still some repetitive code. Each button has a button class. If you though “If only we could use some sort of combination for the last few techniques together” then you’re right. With Sass we can further refactor!
The first step will be to convert our styles to Sass. We’ll remove the curly braces and the semi-colons. If you’re using Scss instead, you won’t have to change anything. This is what we’re left with.
Next we’ll select all the buttons and use the at-extend ( @extend ) rule from Sass to allow the different color classes to inherit the styles from the button class.
And finally, while this part is optional, we’ll hide the button class by using the Placeholder Selector ( % ) from Sass. Doing this will help keep our processed CSS file lighter by hiding the button class from it while still allowing the inheritance to occur.
Learn More
To learn more about Sass / Scss check out the official documentation here:
Check out some of my other Sass / Scss related blog posts!