有没有可能得到 parent 的 parent ?
我尝试了 & & { }
但没有成功。
我正在尝试根据它的祖 parent 来设置子元素的样式。
最佳答案
取决于代码结构,可能需要一些代码重复
在大多数情况下你不能直接这样做(异常(exception)情况见第二个例子)。
如果祖 parent 是一个元素
这需要一些重复,但确实允许祖 parent 不是最外层的包装者(因此可能有曾祖 parent )。
少
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*/
}
如果 Grandparent 是类、ID 等,并且是最外层包装器
此处不涉及重复,但您不能在其中加入曾祖 parent
。此外,这仅适用于 LESS 1.3.1+ 版本(早期版本错误地添加了一个空格):
少
.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*/
}
此代码通过附加到祖 parent 选择器的“前面”来工作,因此这就是祖 parent 必须是类、ID 或其他选择器本身的原因。
附录
基于关于希望在 span
为空时具有红色背景的评论。这不会将背景放在父级上,而是使用子级“伪造”它。
span:empty:after {
content: '';
position: absolute;
top: -1px;
right: -10px;
left: -1px;
bottom: -10px;
display: block;
background-color: red;
z-index: -1;
}
关于css - less-css——是否有可能获得 parent 的 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17286742/