Open In App

What is a @extend directive in SASS ?

Sass is short for Syntactically Awesome Style Sheet. It is an upgrade to Cascading Style Sheets (CSS) and is one of the popular pre-processors available for writing CSS.

The @extend is a keyword in Sass that allows one to share a set of CSS properties from one selector to another. This is useful for reusing styles and making the stylesheet more modular. It is present in all three pre-processors available for CSS.



Working of the @extend directive

Sass uses intelligence unification when extending selectors. Here are the rules as follows:



Difference between @extend and Mixin

This is a general question that comes to every person beginning with Sass. According to the documentation, the following point could be used to remove confusion:

Extension Scope and Placeholder Selectors

Extension Scope: Sass can be said to have upstream flow. This makes its rules predictable and also easy to understand. When one stylesheet extends a selector, then the effect will only be seen on the modules that are upstream and are loaded using the @use or @forward rule and similarly in upstream fashion. This is also referred to as extension scope. 

Placeholder Selectors: Placeholders selectors, as its name describes, are used as placeholders for style. They come into play when you want its extended version in the CSS Output but don’t the style itself. Selectors which are to be used as placeholder selectors start with a percentage (%) and not like general selectors which start with a dot (.).

The below examples demonstrate the @extend directive.

Example 1: Suppose you have two classes, background image and ProfileImage and both require some common styles. The @extend directive can be used as shown in this example.

.backgroundImage{
    border-radius:50%;
    height:100px;
    width:100px;
}

.profileImage{
    @extend .backgroundImage;
    border:none;
}

Output: This will get the compiler to the following CSS Sample.

.backgroundImage, .profileImage {
  border-radius: 50%;
  height: 100px;
  width: 100px;
}

.profileImage {
  border: none;
}

Example 2: For this example, we will be extending multiple classes using the @extend directive.

.backgroundImage{
    border-radius:50%;
    height:100px;
    width:100px;
}

.profileImage{
    @extend .backgroundImage;
    border:none;
    filter: grayscale(100%);
}
.finalImage{
    @extend .profileImage;
}

Output: This gets transpiled to the following CSS.

.backgroundImage, .profileImage, .finalImage {
  border-radius: 50%;
  height: 100px;
  width: 100px;
}

.profileImage, .finalImage {
  border: none;
  filter: grayscale(100%);
}
Article Tags :