Inheritance in Sass
Introduction
Sass means “syntactically awesome style sheet”. Sass is a preprocessor programming language that is interpreted or compiled into Cascading Style Sheets (CSS). The scripting language itself is called SassScript. The sass is saved with .scss or sass extension.
Saas uses Inheritance to make it easier. Few codes are written to carry out different tasks. To minimize the amount of typing and/or combining required, Sass enables us to inherit properties from other selectors.
Suppose we have many divs with the same properties but different font-size. We can define a basic div style where all the divs will inherit from each of their styles. Then they have their own custom styles declared within.
Code example
Inheritance is done in Sass with the @extend rule, this is followed by the selector we want to inherit from.
Let’s look into an example to explain how it works.
Suppose we want to define three divs with the same margin, padding, and font-size but with different color and background-color.
This can be done by defining a selector with the basic properties. We define the selectors of the divs, we make them inherit from the basic selector, and then we define their custom properties.
Let’s look at the code below:
Code explanation
In the CSS (scss) column:
-
Line 1: We declare a class selector with some properties. The name of this selector is
.basicDiv. -
Line 7 : We declare a new class selector,
.blueDiv. The@extendis used so that this selector inherits the properties of the.basicDiv. Then new properties is added to it. -
Lines 13 and 19 : The same process in line 7 was carried out with two new selectors -
.redDivand.whiteDiv.
The scss is then compiled into CSS file.
The compiled CSS will look like this:
All the selectors are defined with .basciDiv's property, and then .blueDiv, .redDiv, and .whiteDiv are defined with their custom properties.
Free Resources