What is the Sass @extend rule?

The Sass @extend rule is a way to share a set of CSS properties from one selector to another selector. It allows you to reuse a set of CSS styles across multiple selectors without having to repeat the same code.

For example, let's say you have a class called .button that defines a set of styles for buttons on your website. You can use the @extend rule to share those styles with another class called .submit-button, like so:

 .button {
  background-color: blue;
  color: white;
  padding: 10px;
}

.submit-button {
  @extend .button;
  font-weight: bold;
}

This will output the CSS as:

.button, .submit-button {
  background-color: blue;
  color: white;
  padding: 10px;
}

.submit-button {
  font-weight: bold;
}

The @extend rule helps to avoid duplication of CSS properties, making the code more maintainable and more scalable. You can also use the %placeholder selectors in Sass to make your code more readable and avoid to use class selector without any semantic meaning.

%button {
  background-color: blue;
  color: white;
  padding: 10px;
}

.submit-button {
  @extend %button;
  font-weight: bold;
}

It's important to note that the @extend rule does not create any HTML elements or classes, it only creates CSS styles. Also, when using the @extend rule, it's important to keep in mind that it can create a lot of unnecessary CSS selectors and styles if it is not used carefully, which can make your CSS code more difficult to maintain and can increase the size of your CSS files. It's also important to note that @extend doesn't work with the !optional flag, this means that if the extending selector doesn't exist, it will cause a compilation error.

In summary, the Sass @extend rule is a way to share a set of CSS properties from one selector to another selector, allowing you to reuse a set of CSS styles across multiple selectors without having to repeat the same code. This can make your code more maintainable and more scalable. However, it's important to use it carefully and avoid creating unnecessary CSS selectors and styles, which can make your CSS code more difficult to maintain and increase the size of your CSS files.

Continue Reading