Sass @extend and Inheritance

The @extend directive tells Sass that a selector's styles are inherited from another selector.

If one style is almost identical to another, with only a few differences, then using @extend becomes very useful.

In the following Sass example, we create a basic button style .button-basic, then we define two button styles .button-report and .button-submit, both of which inherit .button-basic. The main difference is in the background color and font color; the other styles are the same.

Sass code:

.button-basic  {
  border: none;
  padding: 15px 30px;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
}

.button-report  {
  @extend .button-basic;
  background-color: red;
}

.button-submit  {
  @extend .button-basic;
  background-color: green;
  color: white;
}

Convert the above code to CSS code, as shown below:

CSS code:

.button-basic, .button-report, .button-submit {
  border: none;
  padding: 15px 30px;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
}

.button-report  {
  background-color: red;
}

.button-submit  {
  background-color: green;
  color: white;
}

After using @extend, we don't need to specify multiple classes in the HTML button tag like class="button-basic button-report"; we only need to set the class="button-report" class.

@extend is a good demonstration of code reuse.

Other Extensions