Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...