How do I extend a class/mixin which has dynamically formed selector

帅比萌擦擦* 提交于 2019-11-27 05:37:19

Extending a dynamically formed selector (loosely using the term) like that is currently not possible in Less. There is an open feature request to support this. Till it is implemented, here are two work-around solutions to it.

Option 1:

Write the contents of .hello and .hello-world selectors into a separate Less file (say test.less), compile it to get the CSS. Create another file for the rules of .foo, import the compiled CSS as a Less file (using the (less) directive) and then extend the .hello-world as you had originally intended to.

test.less:

.hello {
  &-world {
    color: red;
  }
}

extended-rule.less:

@import (less) "test.css";
.foo {
  &:extend(.hello-world);
  font-size: 20px;
}

Compiled CSS:

.hello-world,
.foo {
  color: red;
}
.foo {
  font-size: 20px;
}

This method would work because by the time the test.css file is imported, the selector is already formed and is no longer dynamic. The drawback is that it needs one extra file and creates dependency.


Option 2:

Write a dummy selector with rules for all properties that need to be applied to both .hello-world and .foo and extend it like:

.dummy{
    color: red;
}
.hello {
  &-world:extend(.dummy) {};
}

.foo:extend(.dummy){
  font-size: 20px;
}

This creates one extra selector (dummy) but is not a big difference.

Note: Adding my comment as an answer so as to not leave the question unanswered and also because the work-around specified in the thread linked in comments doesn't work for me as-is.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!