如何获取父元素的父元素?
我尝试了& & { }
,但没有成功。
我正在尝试根据祖先元素为子元素设置样式。
在大多数情况下不能直接做到这点(请参见第二个例子的例外情况)。
如果祖父元素是一个元素
这需要一些重复,但允许祖父元素不是最外层包装器(因此可能存在曾祖父)。
LESS
grandparent {
/* grandparent styles */
parent {
/* parent styles */
child {
/* child styles */
}
}
&.specialGrandpa {
child {
/* child styles with special Grandpa */
}
}
&.specialGrandma {
child {
/* child styles with special Grandma*/
}
}
}
CSS 输出
grandparent {
/* grandparent styles */
}
grandparent parent {
/* parent styles */
}
grandparent parent child {
/* child styles */
}
grandparent.specialGrandpa child {
/* child styles with special Grandpa */
}
grandparent.specialGrandma child {
/* child styles with special Grandma*/
}
如果“祖先”是一个类、ID等,并且是最外层的包装器
这里没有重复,但不能在混合中有一个“曾祖父”。另外,这仅适用于LESS 1.3.1+版本(早期版本不正确地添加了一个空格):
LESS
.grandparent {
/* grandparent styles */
.parent {
/* parent styles */
.child {
/* child styles */
.specialGrandparent& {
/* child styles with special grandparent*/
}
}
}
}
CSS 输出
.grandparent {
/* grandparent styles */
}
.grandparent .parent {
/* parent styles */
}
.grandparent .parent .child {
/* child styles */
}
.specialGrandparent.grandparent .parent .child {
/* child styles with special grandparent*/
}
这段代码是通过在祖先选择器的“前面”添加内容来实现的,因此祖先必须是一个类、ID或其他选择器本身。
附加说明
基于关于希望在为空时具有红色背景的评论。这不会将背景放在父元素上,而是使用子元素“伪造”它。
span:empty:after {
content: '';
position: absolute;
top: -1px;
right: -10px;
left: -1px;
bottom: -10px;
display: block;
background-color: red;
z-index: -1;
}
如果要遍历DOM树并选择元素,使用javascript而不是less选择器。
在less中,&
表示声明的选择器向上移动一级。这是已定义规则的快捷方式。与您所寻找的相反。
&
放在项目后面来访问项目的父级父级,从而实现更改选择器顺序。请保留HTML标签。
LESS代码:
span {
color:red;
h6 & {
color:white;
div & {
color:blue;
}
}
}
CSS结果:
span {
color: red;
}
h6 span {
color: white;
}
div h6 span {
color: blue;
}
ul {
.color-links(@color) {
li a { // any link inside a child li
color: @color;
}
}
&.red {
.color-links(#ff0000);
}
&.green {
.color-links(#00ff00);
}
}
span
是否为空(处理是在它被发送到浏览器之前完成的;它没有关于html状态的知识),并且CSS不能基于子元素的状态影响父元素。你需要使用JavaScript来实现你想要的功能。 - ScottSspan:empty:after
以应用背景。代码作为我的答案附录给出。 - ScottSspan:empty:after
代码插入到你的无法工作的代码位置,你就会看到它给你带来了什么(当span
为空时,div
会有一个红色背景)。 - ScottS