sass
  1. sass-inheritance

SASS Inheritance

Syntax

SASS inheritance allows you to create a class that inherits the properties of another class. The syntax for SASS inheritance is as follows:

.class-name {
  @extend .other-class-name;
}

Example

Let’s say you want to create multiple button styles. Instead of duplicating styles, SASS inheritance can be used to create a base class and extend its properties to create a new class.

.button-base {
  padding: 10px;
  border-radius: 5px;
  background-color: #ff0000;
  color: #fff;
  font-size: 18px;
}

.button-special {
  @extend .button-base;
  background-color: #0000ff;
  font-size: 20px;
}

Output

The output for the example code above would be:

.button-base, .button-special {
  padding: 10px;
  border-radius: 5px;
  background-color: #ff0000;
  color: #fff;
  font-size: 18px;
}

.button-special {
  background-color: #0000ff;
  font-size: 20px;
}

Explanation

In the example above, a base class .button-base is created with some basic properties for the button. Then, a new button class .button-special is created by extending the properties of .button-base.

@extend .button-base; inherits all of the properties of .button-base and applies them to .button-special. The background-color and font-size properties are overridden in .button-special to create a new button class with different properties.

Use

SASS inheritance can be useful in situations where multiple classes share a common set of properties. It allows for cleaner code and prevents the need for duplicating styles. It can also save time during development and make it easier to manage and update styles.

Important Points

  • Inheritance is a powerful feature in SASS that can help reduce code duplication and improve maintainability.
  • Inherited properties will be combined with the current selector.
  • Inherited properties can be overwritten by specifying the same property in the inheriting class.
  • Care should be taken when using inheritance to ensure that changes to the base class don't break any of the inheriting classes.

Summary

SASS inheritance allows you to create classes that inherit properties from other classes, reducing code duplication and making it easier to manage and update styles. It provides a powerful tool for managing complex styling requirements.

Published on: