Chuck's Academy

CSS Preprocessors

Extensions and Inheritance in Sass

In addition to mixins, Sass offers another powerful tool for code reuse called "extensions" or "inheritance". Using the @extend directive, you can share a set of CSS rules among multiple selectors. This capability makes your CSS more efficient and maintains a DRY (Don't Repeat Yourself) approach.

@extend Concept

The @extend directive allows a selector to acquire all the properties of another selector, as if it were inheriting its characteristics. It is especially useful for styles that are repeated across several elements.

Basic Example

scss

CSS Result:

css

Extension and Specificity

The @extend directive combines selectors in the resulting CSS, which can increase or decrease the specificity of your selectors depending on how and where you use it.

Example:

scss

CSS Result:

css

Inheritance in Nested Selectors

@extend can also be used in nested selectors to share rules among nested selectors.

scss

Limitations of @extend

Although @extend is very useful, it also has some limitations and disadvantages that you should be aware of:

  1. Specificity:

    • It can generate unexpectedly specific or general selectors, complicating style management.
  2. Maintenance:

    • Changes to extended selectors can affect multiple elements, which can be difficult to maintain in large projects.
  3. Performance:

    • It can generate larger final CSS due to the combination of selectors.

Using Placeholders with %

To avoid specificity issues and improve performance, you can use placeholders instead of classes. Placeholders are defined using the % prefix and are not rendered in the final CSS unless they are extended.

Example with Placeholders

scss

CSS Result:

css

Complete Example

Let's see a more complete example that shows how to combine @extend and % placeholders to create a reusable and modular component.

scss

Conclusion

Inheritance and extensions in Sass provide a powerful way to share styles among multiple elements without duplicating code. However, it is important to use @extend with caution due to its limitations in terms of specificity and performance. Using placeholders can help you mitigate some of these issues and improve the modularity of your CSS. In the next chapter, we will explore functions and operations in Sass, which will add even more dynamism and flexibility to your stylesheets.


Ask me anything