Skip to content
Related Articles

Related Articles

What is the use of extend in LESS ?

Improve Article
Save Article
Like Article
  • Last Updated : 15 Dec, 2021

LESS is one of the most popular CSS preprocessor languages because of its many features like mixins, imports, variables and so on which helps to reduce the complexity of CSS code. One such important and useful feature of LESS is the @extend directive. In this article, we will learn about the use of the extend feature in LESS.

Extend in LESS helps us to merge different selectors it is put on with. We can use the LESS extend feature using the :extend keyword.

Syntax:

.elem1:extend(.elem1){};

It can also be used inside a class to extend the properties of a class.

&:extend(.elem1);

 

Example 1: We use the extend feature inside the .btn2 block to extend the feature of the .btn1 class.

.btn1{
    background-color: blue;
    border: 2px solid white;
}
.btn2{
    color: whitesmoke;
    &:extend(.btn1);
}

Output:

CSS




.btn1,
.btn2 {
  background-color: blue;
  border: 2px solid white;
}
.btn2 {
  color: whitesmoke;
}

Example 2: In this example, .btn2 is extended with the .btn1 class.

.btn1{
    background-color: blue;
    border: 2px solid white;
}
.btn2:extend(.btn1){};

Output:

CSS




.btn1,
.btn2 {
  background-color: blue;
  border: 2px solid white;
}

We can also extend multiple selectors into one selector. This can be done using two different methods. Syntax of both is the method are given below:

Extending Interpolated Selectors: The extend keyword cannot be used to match selectors with variables but it works with interpolated variables.  

Example 1:

@variable: .heading2;
@{variable} {
  color: blue;
}
.heading1:extend(.heading2) {}

Output:

CSS




.heading2{
  color: blue;
}

Example 2:

.heading1 {
  color: blue;
}
@{variable}:extend(.heading1) {}
@variable: .heading2;

Output:

CSS




.heading1, .heading2 {
  color: blue;
}

Extend inside the @media: If we call extend from the inside of @media, it will only match the selectors inside the media and the rest will be left alone. Given below is a code example that shows the following, in which we have to extend a selector inside @media braces. The below example explains this.

Example:

@media print {
    .head1:extend(.head2) {}
    .head2 {
      color: black;
    }
  }
  .head2 {
    color: red;
  }
  @media screen {
    .head2 {
      color: blue;
    }
  }

Output: Extend only extends those selectors are inside the same @media and ignores everything else.

CSS




@media print {
  .head2,
  .head1 {
    color: black;
  }
}
.head2 {
  color: red;
}
@media screen {
  .head2 {
    color: blue;
  }
}

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!