How can you share CSS properties from one selector to another in Sass?

Sharing CSS Properties between Selectors using the @extend Directive in Sass

In Sass, a powerful CSS preprocessor, the @extend directive is used to share CSS properties from one selector to another. This allows developers to create re-usable rules and keeps code DRY (Don't Repeat Yourself), for enhanced maintainability.

Let's delve into a clear example of how this can be used:

Consider we have two types of buttons in our HTML document - a base button and a special button, which shares some properties of the base button but has few extra unique properties.

.base-button {
  border: none;
  padding: 15px 32px;
  text-align: center;
}

.special-button {
  @extend .base-button;
  background-color: red;
  color: white;
}

In the above code, .special-button is extending .base-button meaning all the properties of .base-button will be included in .special-button. Therefore, .special-button has border, padding, text-align, background-color and color properties.

In the compiled CSS, the selectors extending the same rules will be grouped together, improving code efficiency and readability:

.base-button, .special-button {
  border: none;
  padding: 15px 32px;
  text-align: center;
}

.special-button {
  background-color: red;
  color: white;
}

As developers, the @extend directive should be used judiciously. Overuse can lead to large CSS files and properties being inherited in unexpected ways. It's recommended to use @extend for tightly related selectors and @mixin for fragments of styles that may change.

Remember that @extend is just one of the advanced features Sass provides to streamline your CSS coding. Explore others such as variables, mixins, and nesting to advance your CSS proficiency.

Do you find this helpful?