问题
From documentation about changing selector order we can see this example:
.header {
.menu {
border-radius: 5px;
.no-borderradius & {
background-image: url('images/button-background.png');
}
}
}
and result will be
.no-borderradius .header .menu {}
How to use parent-selector &
to get selector .header .menu.no-borderradius
without duplicating code:
ul {
li {
a {
.active &,
&:hover {
color: red;
}
}
}
}
will provide CSS
.active ul li a {color: red;}
but required result is
ul li.active a {color: red;}
回答1:
You have put the &
(parent selector) at the wrong place. It shouldn't be put after the selector, instead it should be before the .
. Setting the &
after the selector means the whole parent selector (from the topmost selector) will be appended at the end of the current selector instead of getting inserted before (which is what you need for .header .menu.no-borderradius
or ul li.active
.
.header {
.menu {
border-radius: 5px;
&.no-borderradius { /* here & is equal to .header .menu */
background-image: url('images/button-background.png');
}
}
}
ul {
li {
&.active, /* here & is equal to ul li */
&:hover {
color: red;
}
}
}
Regarding the update to the question - it is currently not possible to achieve ul li.active a
using the below structure as parent selector means the entire chain of selectors till the current level and not just the immediate parent. There is no way to just pick the immediate parent.
ul {
li {
a {
.active &,
&:hover {
color: red;
}
}
}
}
The only option currently possible is to write it like below:
ul {
li {
&.active a,
a:hover {
color: red;
}
}
}
There is an open feature request for parent selectors to have targets but there is no decision on by when this would be done.
来源:https://stackoverflow.com/questions/36908818/less-parent-selector-for-first-parent