Categories
CSS Web development

Sass @extend/ Inheritance

The @extend directive in Sass is a powerful directive that facilitates the sharing of rules and relationships between selectors.

Sass

The @extend directive lets you share a set of CSS properties from one selector to another. It helps keep your Sass very DRY.

The @extend directive is useful if you have almost identically styled elements that only differ in some small details.

The following Sass example first creates a basic style for buttons (this style will be used for most buttons). Then, we create one style for a “Report” button and one style for a “Submit” button. Both “Report” and “Submit” button inherit all the CSS properties from the .button-basic class, through the @extend directive. In addition, they have their own colors defined:

SCSS Syntax:

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

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

.button-submit  {
  @extend .button-basic;
  background-color: yellow;
  color: black;
}

After compilation, the CSS will look like this:

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

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

.button-submit  {
  background-color: yellow;
  color: black;
}

Enjoy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *