sass
  1. sass-extending-selectors

SASS Extending Selectors

Syntax

SASS provides the @extend directive to extend the selectors and properties of existing CSS rules. Here is the basic syntax for extending selectors in SASS:

.selector {
  // some properties here
}

.new-selector {
  @extend .selector;
  // additional properties here
}

Example

Let's say we have a button style defined as follows:

.btn {
  font-size: 16px;
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
}

We can extend this button style to create a secondary button style like this:

.btn-secondary {
  @extend .btn;
  background-color: #6c757d;
}

Output

The resulting CSS output for the above SASS code will be:

.btn, .btn-secondary {
  font-size: 16px;
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
}

.btn-secondary {
  background-color: #6c757d;
}

Explanation

Extending selectors is a way to avoid duplicating CSS code. When we extend a selector, we basically inherit all of its properties in the extended selector. In the above example, we extended the .btn selector to create a new selector .btn-secondary. The .btn-secondary selector now inherits all the properties of the .btn selector, except for the background-color property, which we have overridden with a different value.

Use

Extending selectors is useful in situations where we want to create variants of existing styles. This saves us time and effort, since we don't have to rewrite the entire CSS code for each variation. Instead, we can create a base style and then extend it to create variations as needed.

Important Points

  • Selectors can be extended by placing an @extend rule inside another selector block.
  • Extending a selector will inherit all the properties of the original selector, including any pseudo-selectors.
  • Extending a selector will also add the extending selector to the combined CSS output, even if it doesn't appear in the HTML markup.

Summary

SASS provides the @extend directive to extend selectors and properties of existing CSS rules. This is a powerful tool for creating new styles based on existing ones, and can save time and effort in CSS authoring. It's important to use it judiciously and be aware of how it affects the resulting CSS output.

Published on: