Sass/SCSS Inheritance Tutorial

In this Sass/SCSS tutorial we learn how to inherit properties from one selector in another with the @extend rule.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

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.

Syntax: Sass
selector-1 {
  property: value;
}

selector-2 {
  @extends selector-1;

  property: value;
}

The compiler doesn’t copy the properties from selector-1 into selector-2 .

Instead it defines both selectors with all of selector-1 ’s properties and then defines selector-2 with its extra properties.

Example: SCSS
.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.

Output: Compiled CSS
.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 .

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.