我将用一个例子来解释。
想象一下以下的CSS规则
.parent {
color: blue;
}
.child {
color: red;
}
.parent .child {
color: white;
}
现在,假设你想使用LESS创建一个等同于.parent
的类和另一个等同于.child
的类。
如果您使用“延伸”,您将实现目标的一部分:
.newParent {
&:extend(.parent all);
}
.newChild {
&:extend(.child all);
}
将呈现:
.parent,
.newParent {
color: blue;
}
.child,
.newChild {
color: red;
}
.parent .child,
.newParent .child,
.parent .newChild {
color: white;
}
这使您的新课程几乎等同于旧课程。
最后一组规则中缺少.newParent .newClass
。
有没有办法实现这种完全等同?
注意:这可能对使用Bootstrap并希望为其类使用其他名称的人有所帮助(从框架中实现更大的抽象)。例如,假设您要更改.input-append
和.add-on
的名称,为此您需要扩展与这两个类相关的所有选择器,包括出现这两个类的选择器(如{{ 1}})。
提前致谢!
答案 0 :(得分:6)
all
选项会将 new 选择器添加到已存在的所有层次关系/嵌套选择器中。
因此,在使用.parent .child
扩展.parent
时,在嵌套选择器.newParent
中,它将使用.newParent .child
扩展嵌套选择器,因为与.child
的此关系具有已定义。使用.child
扩展.newChild
时,嵌套选择器会延长.parent .newChild
,因为.child
和.parent
之间存在关系。你最终得到了这个 CSS :
.parent .child,
.newParent .child,
.parent .newChild {
color: white;
}
注意:这不会创建基于使用扩展名创建的嵌套选择器的选择器。在扩展之前,既没有.newParent .child
的定义,也没有.parent .newChild
的定义,这可能导致在规则扩展后创建.newParent .newChild
。
我不完全确定您希望CSS输出看起来多么精确,但您也可以随时扩展“ relationship ”/ combined / nested选择器并避免使用all
选项,这样您就不会生成所有混合选择器(例如.parent .newChild
和.newParent child
):
.newParent {
&:extend(.parent);
}
.newChild {
&:extend(.child);
}
.newParent .newChild {
&:extend(.parent .child);
}
或以嵌套形式:
.newChild {
&:extend(.child);
}
.newParent {
&:extend(.parent);
.newChild {
&:extend(.parent .child);
}
}
并且 CSS 输出将为:
.parent,
.newParent {
color: blue;
}
.child,
.newChild {
color: red;
}
.parent .child,
.newParent .newChild {
color: white;
}
如果需要,您现在可以通过添加all
选项简单地添加所有嵌套选择器组合。这将为您提供选择器的所有排列,并且可以实现 CSS :
.parent,
.newParent {
color: blue;
}
.child,
.newChild {
color: red;
}
.parent .child,
.parent .newChild,
.newParent .child,
.newParent .newChild {
color: white;
}