Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

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

How do I extend a Less class which is dynamically formed using & combinator?

Less which generates expected output:

.hello-world {
  color: red;
}

.foo {
  &:extend(.hello-world);
  font-size: 20px;
}

Expected CSS output:

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

Less does not generate expected output:

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

.foo {
  &:extend(.hello-world);
  font-size: 20px;
}

Unexpected CSS output:

.hello-world {
  color: red;
}
.foo {
  font-size: 20px;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...