Does LESS have an "extend" feature?

CssSassLessExtend

Css Problem Overview


SASS has a feature called @extend which allows a selector to inherit the properties of another selector, but without copying the properties (like mixins).

Does LESS have this feature as well?

Css Solutions


Solution 1 - Css

Yes, Less.js introduced extend in v1.4.0.

:extend()

Rather than implementing the at-rule (@extend) syntax used by SASS and Stylus, LESS implemented the pseudo-class syntax, which gives LESS's implementation the flexibility to be applied either directly to a selector itself, or inside a statement. So both of these will work:

.sidenav:extend(.nav) {...}

or

.sidenav {
    &:extend(.nav);
    ...
}

Additionally, you can use the all directive to extend "nested" classes as well:

.sidenav:extend(.nav all){};

And you can add a comma-separated list of classes you wish to extend:

.global-nav {
    &:extend(.navbar, .nav all, .navbar-fixed-top all, .navbar-inverse);
    height: 70px;
}

When extending nested selectors you should notice the differences:

nested selectors .selector1 and selector2:

.selector1 {
  property1: a;
   .selector2 {
    property2: b;
   }
}

Now .selector3:extend(.selector1 .selector2){}; outputs:

.selector1 {
  property1: a;
}
.selector1 .selector2,
.selector3 {
  property2: b;
}

, .selector3:extend(.selector1 all){}; outputs:

.selector1,
.selector3 {
  property1: a;
}
.selector1 .selector2,
.selector3 .selector2 {
  property2: b;
}

,.selector3:extend(.selector2){}; outputs

.selector1 {
  property1: a;
}
.selector1 .selector2 {
  property2: b;
}

and finally .selector3:extend(.selector2 all){};:

.selector1 {
  property1: a;
}
.selector1 .selector2,
.selector1 .selector3 {
  property2: b;
}

Solution 2 - Css

Easy way to extend a function in Less framework

.sibling-1 {
    color: red
}
.sibling-2 {
    background-color: #fff;
    .sibling-1();
}

>Output

.sibling-1 {
  color: red
}
.sibling-2 {
  background-color: #fff;
  color: red
}

Refer https://codepen.io/sprushika/pen/MVZoGB/

Solution 3 - Css

Less allows us to do :extend(.class) or :extend(#id)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjonschlinkertView Question on Stackoverflow
Solution 1 - CssjonschlinkertView Answer on Stackoverflow
Solution 2 - CssSpushika MulakalaView Answer on Stackoverflow
Solution 3 - CssSudharshan SView Answer on Stackoverflow