Explain what is a @extend directive used for in Sass?

In Sass (Syntactically Awesome Style Sheets), the @extend directive is used to share styles from one CSS selector to another. It allows you to create a relationship between two or more selectors, where one selector inherits the styles of another selector.

The @extend directive helps to promote code reusability and maintainability by reducing duplication of styles. Instead of rewriting the same styles for multiple selectors, you can define the styles once and extend them to other selectors when needed.

Here’s an example to illustrate the usage of the @extend directive in Sass:

.error {
  color: red;
  font-weight: bold;
}

.warning {
  @extend .error;
  background-color: yellow;
}

.success {
  @extend .error;
  color: green;
}

In this example, the .error selector defines styles for elements with error messages. The .warning selector and .success selector both use the @extend directive to inherit the styles from the .error selector. This means that any element with the class .warning or .success will have the styles defined in the .error selector, in addition to their own specific styles.

After Sass processes the above code, the resulting CSS will be:

.error, .warning, .success {
  color: red;
  font-weight: bold;
}

.warning {
  background-color: yellow;
}

.success {
  color: green;
}

As you can see, the styles defined in the .error selector are applied to all three selectors: .error, .warning, and .success. The @extend directive combines the styles, resulting in cleaner and more concise code.

It’s worth noting that when using @extend, Sass generates a comma-separated list of selectors in the CSS output. This can be useful for performance optimization, as it reduces the number of selectors to match against elements.

However, it’s important to use the @extend directive judiciously. It’s best suited for cases where you want to share common styles between selectors. Overusing @extend can result in excessive specificity and bloated CSS output, so it’s recommended to use it sparingly and with caution.

error: Content is protected !!