问题
I need this CSS:
.class-1.class-a .target {
background: red;
}
.class-1.class-b .target {
background: blue;
}
I've got this working fine with this Less
.target {
.class-1.class-a & {
background: red;
}
.class-1.class-b & {
background: blue;
}
}
However can my LESS be written more succinctly? Its seems a shame to write class-1 twice. I've tried this:
.target {
.class-1 & {
&.class-a {
background: red;
}
&.class-b {
background: blue;
}
}
}
And also this:
.target {
.class-1 & {
.class-a & {
background: red;
}
.class-b & {
background: blue;
}
}
}
回答1:
Your last attempt is pretty close, if you modify it like:
.target {
.class-1 & {
.class-a& {
background: red;
}
.class-b& {
background: blue;
}
}
}
it will work.
Note that the order of classes of the same level does not matter, thus the resulting .class-a.class-1 .target
is equal to desired .class-1.class-a .target
(I'm not mentioning though that usually the idea of avoiding repetitions by any cost is flawed. All those cryptic chains of ampersands and brackets make the code totally unreadable if compared to your initial code and even pure CSS itself).
来源:https://stackoverflow.com/questions/34727945/have-2-classes-as-parent-selectors-at-different-levels-in-less