Curriculum
Course: Sass Tutorial
Login
Text lesson

Sass @extend Directive

The @extend directive proves beneficial when dealing with elements that share almost identical styles but vary slightly in certain aspects.

In the following Sass example, a foundational style for buttons is initially established, intended for widespread usage across most buttons. Subsequently, separate styles are crafted for a “Report” button and a “Submit” button. Both “Report” and “Submit” buttons inherit all CSS properties from the .button-basic class via the @extend directive. Additionally, they each have their unique color definitions:

SCSS Syntax:

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

Upon compilation, the resulting CSS will be structured as follows:

CSS Output:

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

Utilizing the @extend directive eliminates the necessity of specifying multiple classes for an HTML element in your code, as depicted in the example: <button class=”button-basic button-report”>Report this</button>. Simply specifying .button-report suffices to acquire both sets of styles.

This practice ensures the conciseness and adherence to the DRY (Don’t Repeat Yourself) principle within your Sass code.