Search code examples
csslessmixins

LESS extend is not working for the imported css


I'm trying to combine class names in to one using LESS extend mixin and this simple example is not giving expected results:

@import (less) "//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css";

.todoFlag:extend(.fa .fa-flag all) {
    color: red;
}

The .fa-flag class above in imported css has only one selector like this:

.fa-flag:before {
  content: "\f024";
}

The result of compilation is this:

.todoFlag {
  color: red;
}

I was expecting .todoFlag will have :before due to extend but above is the only lines generated for todoFlag in compiled css.

Am I using the extend correctly? Does extend works on classes imported like above?


Solution

  • I finally figured out (thanks to Mária Jurčovičová's excellent writeup on this "hidden" feature of LESS).

    The .todoFlag:extend(.fa .fa-flag all) actually extends fa-flag as descendant on fa. In reality fa-flag is not a descendant of fa so that statement has no effect. What I'd actually like to achieve was replace the multiple classes in to one class. So if you have,

    <i class="fa fa-flag redColor"></i>
    

    I want to replace that with,

    <i class="todoFlag"></i>
    

    To do this, todoFlag needs to first inherit everything from fa, including all pseudo selectors such as :after and then it needs to inherit from fa-flag. To achieve this, we need to use a feature of LESS extend that allows this kind of multiple inheritance. The syntax for this is,

    .todoFlag:extend(.fa all):extend(.fa-flag all) {
        .redColor;
    }
    

    So basically, you call extend twice with each class. And it works!