本文为http://lesscss.org/features/ Parent Selector部分的翻译。
父 选择器
用
&来引用
父选择器(译注:大多数情况,&表示将所有的祖先选择器替换在它的位置)
&操作符最常用在嵌套规则中,表示一个应用修改类或伪类的既有选择器的父选择器,例如
a {
color: blue;
&:hover {
color: green;
}
}
结果是:
a {
color: blue;
}
a:hover {
color: green;
}
请注意如果没有使用&
,则上面的示例将产生a :hover
规则(与<a>
标记内悬停元素匹配的后代选择器),而这并不是我们通常想要使用的紧跟在a后面的:hover
。
“父选择器”运算符有多种用途。基本上,用于嵌入选择器的组合会比默认的情况要多见。。例如,&
的另一种典型用法是产生重复的类名:
.button {
&-ok {
background-image: url("ok.png");
}
&-cancel {
background-image: url("cancel.png");
}
&-custom {
background-image: url("custom.png");
}
}
输出:
.button-ok {
background-image: url("ok.png");
}
.button-cancel {
background-image: url("cancel.png");
}
.button-custom {
background-image: url("custom.png");
}
多 多重&
&
在选择器中可能会出现多次,用于重复引用父选择器而无需重复其名称。
.link {
& + & {
color: red;
}
& & {
color: green;
}
&& {
color: blue;
}
&, &ish {
color: cyan;
}
}
输出为:
.link + .link {
color: red;
}
.link .link {
color: green;
}
.link.link {
color: blue;
}
.link, .linkish {
color: cyan;
}
请注意,&
代表所有父选择器(而不仅仅是最接近的祖先),因此下例:
.grand {
.parent {
& > & {
color: red;
}
& & {
color: green;
}
&& {
color: blue;
}
&, &ish {
color: cyan;
}
}
}
结果是:
.grand .parent > .grand .parent {
color: red;
}
.grand .parent .grand .parent {
color: green;
}
.grand .parent.grand .parent {
color: blue;
}
.grand .parent,
.grand .parentish {
color: cyan;
}
更改选择器顺序
将选择器放在继承的(父)选择器之前可能很有用。这可以通过将&放在
在当前选择器之后来完成。例如,在使用Modernizr时,您可能要根据支持的功能指定不同的规则:
.header {
.menu {
border-radius: 5px;
.no-borderradius & { //父子关系反过来了
background-image: url('images/button-background.png');
}
}
}
选择器.no-borderradius &
将.no-borderradius
在其父项.header .menu
之前得到.no-borderradius .header .menu
输出:
.header .menu {
border-radius: 5px;
}
.no-borderradius .header .menu {
background-image: url('images/button-background.png');
}
组合爆发(Combinatorial Explosion)
&
也可以用于生成逗号分隔列表中选择器所有的可能排列组合:
p, a, ul, li {
border-top: 2px dotted #366;
& + & {
border-top: 0;
}
}
这将扩展为指定元素的所有可能(16种)组合:
p,
a,
ul,
li {
border-top: 2px dotted #366;
}
p + p,
p + a,
p + ul,
p + li,
a + p,
a + a,
a + ul,
a + li,
ul + p,
ul + a,
ul + ul,
ul + li,
li + p,
li + a,
li + ul,
li + li {
border-top: 0;
}