Easy Tutorial
❮ Sass Functions Sass String Func ❯

Sass @extend and Inheritance

The @extend directive tells Sass to inherit the styles of one selector from another.

If a style is almost identical to another, with only a few differences, using @extend can be 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 inheriting from .button-basic. The main differences between them are the background color and font color, while other styles remain 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;
}

Converting the above code to CSS, it looks like this:

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;
}

Using @extend, we don't need to specify multiple classes in the HTML button tags, such as class="button-basic button-report". Instead, we can simply set the class="button-report".

@extend effectively demonstrates code reusability.

❮ Sass Functions Sass String Func ❯