What is the Sass @extend directive?

Sass is a powerful CSS pre-processor that allows you to write more efficient and maintainable stylesheets. One of the features that Sass provides is the @extend directive, which allows you to share a set of CSS properties from one selector to another.

The @extend directive is used to make a CSS class inherit the styles of another class. This allows you to avoid duplicating CSS code and keep your stylesheets organized and maintainable. For example, if you have a .btn class with some basic button styles, and you want to create a new class .danger-btn that inherits those styles and adds a few more, you can use the @extend directive to do so.

.btn {
  background-color: blue;
  color: white;
  padding: 10px;
  border: none;
  font-size: 16px;
}

.danger-btn {
  @extend .btn;
  background-color: red;
}

In this example, .danger-btn will have all the styles of .btn class and in addition it will have a red background color.

It's worth noting that the @extend directive creates a relationship between selectors, not between the styles themselves. This means that if you change a style in the parent class, it will automatically be updated in all child classes that use @extend. However, if you override a style in the child class, that style will not be affected by changes in the parent class.

Also, the @extend directive only works between selectors of the same type, for example, classes cannot extend element selectors or placeholders.

Sass @extend directive is an extremely useful tool for creating maintainable and reusable styles. It allows you to share common styles between multiple selectors and keeps your code organized and easy to read. Keep in mind that it creates relationship between selectors and it can only be used between selectors of the same type.

Continue Reading