Less允许选择父选择器(http://lesscss.org/features/#parent-selectors-feature)
如何获得直接父选择器,而不是根父选择器?
答案 0 :(得分:34)
这在一定程度上取决于你如何构建你的LESS代码。 目前无法使用常规嵌套结构执行此操作。但是,请采用以下示例,其中.grandchild
是我们在所有情况下的最终目标(它必须是最外层 - - 在LESS添加关于使用&
作为父选择器的文档之前,我在之前的答案中称之为“end target grouping”:
<强> LESS 强>
.grandchild {
grandchild: 1;
.child & {
child: 1;
.parent & {
parent: 1;
.grandparent & {
grandparent: 1;
}
}
}
}
CSS输出
.grandchild {
grandchild: 1;
}
.child .grandchild {
child: 1;
}
.parent .child .grandchild {
parent: 1;
}
.grandparent .parent .child .grandchild {
grandparent: 1;
}
如您所见,嵌套在第一级中的任何代码在其选择器字符串中仅具有.grandchild
的结束目标。每个级别一个在巢中“向下”,一个实际上在选择器特异性中“向上”。因此,要仅为选择器字符串的“直接父级”定位,请将其放在此示例的.child
中。
<强> LESS 强>
.grandchild {
grandchild: 1;
&:hover {
grandchildhover: 1;
}
.child & {
child: 1;
.parent & {
parent: 1;
.grandparent & {
grandparent: 1;
&:hover {
grandchildhover: 1;
}
}
}
}
}
这将为上述css添加这两个输出:
.grandchild:hover {
grandchildhover: 1;
}
.grandparent .parent .child .grandchild:hover {
grandchildhover: 1;
}
您可以将其编码为跳过几代,例如:
<强> LESS 强>
.grandchild {
grandchildonly: 1;
.child & {
withchild: 1;
.parent & {
withparentchild: 1;
}
}
.parent & {
skipgenchild: 1;
}
}
CSS输出
.grandchild {
grandchildonly: 1;
}
.child .grandchild {
withchild: 1;
}
.parent .child .grandchild {
withparentchild: 1;
}
.parent .grandchild {
skipgenchild: 1;
}
可以通过各种方式将其抽象出来,这样代码就不会出现嵌套外观(这可能会使用户感到困惑)。这样的东西是单向的(输出类似于上面第一和第二个例子中给出的):
.addParent(@parent) {
@parentescaped: e(@parent);
@{parentescaped} & {.setWithParentProps(@parent);}
}
.grandchild {
grandchild: 1;
&:hover {
grandchildhover: 1;
}
.addParent('.child');
.setWithParentProps('.child'){
child: 1;
.addParent('.parent');
}
.setWithParentProps('.parent'){
parent: 1;
.addParent('.grandparent');
}
.setWithParentProps('.grandparent'){
grandparent: 1;
&:hover {
morespecifichover: 1;
}
}
}
正如他的评论there is talk of adding generational precision within a normal nested context中所涉及的七阶段最大值。这里给出的解决方案要求人们思考嵌套的“相反”,而只考虑被定位的元素。因此,将.grandchild
添加到另一个选择器 的方式不会是 mixin:
LESS(期望通过正常嵌套添加父级)
.another-generational-parent {
.grandchild;
}
CSS输出
.another-generational-parent {
grandchildonly: 1;
}
.child .another-generational-parent {
withchild: 1;
}
.parent .child .another-generational-parent {
withparentchild: 1;
}
最好根据正确的位置将其添加到原始代码中,但如果不可能,则需要重复一些(除非您在原始代码中设置某种方式以通过广告素材“插入”父级mixin调用 - 我没有时间虔诚于此。)
.parent .child .grandchild {
.another-generational-parent & {
another-generational-parent: 1;
}
}
这种相反的编码是否有用都取决于一个人在组织LESS代码时的目标和愿望。