LESS:当两个类之间存在关系时,如何完全扩展两个类

Tom*_*lio 4 less twitter-bootstrap

我将用一个例子来解释.

想象一下以下的CSS规则

.parent {
  color: blue;
}
.child {
  color: red;
}
.parent .child {
  color: white;
}
Run Code Online (Sandbox Code Playgroud)

现在,想象一下你想要创建一个等同于.parent另一个等同于.child使用LESS的类.

如果您使用"extend",您将实现目标的一部分:

.newParent {
  &:extend(.parent all);
}
.newChild {
  &:extend(.child all);
}
Run Code Online (Sandbox Code Playgroud)

将呈现:

.parent,
.newParent {
  color: blue;
}
.child,
.newChild {
  color: red;
}
.parent .child,
.newParent .child,
.parent .newChild {
  color: white;
}
Run Code Online (Sandbox Code Playgroud)

这使得你的新课程几乎等同于你的旧课程.

丢失.newParent .newClass来自最后一组规则.

有没有办法实现这种完全等价?

注意:这对于使用Bootstrap并希望为其类使用其他名称的人(对于从框架实现更大的抽象)可能有所帮助.例如,假设您要更改名称,.input-append并且.add-on您需要为此扩展与这两个类相关的所有选择器,包括其中两个类都出现的选择器(如.input-append .add-on { ... }).

提前致谢!

Mar*_*jak 6

all选项将选择器添加到已存在的所有层次关系/嵌套选择器.

所以,在选择嵌套.parent .child时延伸.parent.newParent它会扩展与嵌套的选择.newParent .child,因为这种关系.child已经被定义.当延长.child.newChild,嵌套选择器得到由扩展.parent .newChild,因为之间的关系.child.parent存在.你最终得到这个CSS:

.parent .child,
.newParent .child,
.parent .newChild {
  color: white;
}
Run Code Online (Sandbox Code Playgroud)

注意:这不会基于使用扩展名创建的嵌套选择器创建选择器.在扩展之前既没有定义.newParent .child也没有定义.parent .newChild,这可能导致在.newParent .newChild规则扩展之后创建.

我不完全确定你希望你的CSS输出看起来多么精确,但是你总是可以扩展" 关系 "/组合/嵌套选择器并避免使用该all选项,这样你就不会生成所有的混合选择器(比如.parent .newChild并且.newParent child):

.newParent {
  &:extend(.parent);
}
.newChild {
  &:extend(.child);
}
.newParent .newChild {
  &:extend(.parent .child);
}
Run Code Online (Sandbox Code Playgroud)

或以嵌套形式:

.newChild {
  &:extend(.child);
}
.newParent {
   &:extend(.parent);
   .newChild {
      &:extend(.parent .child);
   }
}
Run Code Online (Sandbox Code Playgroud)

并且CSS输出将是:

.parent,
.newParent {
  color: blue;
}
.child,
.newChild {
  color: red;
}
.parent .child,
.newParent .newChild {
  color: white;
}
Run Code Online (Sandbox Code Playgroud)

如果需要,您现在可以通过添加all选项简单地添加所有嵌套选择器组合.这将为您提供选择器的所有排列,并获得此CSS:

.parent,
.newParent {
  color: blue;
}
.child,
.newChild {
  color: red;
}
.parent .child,
.parent .newChild,
.newParent .child,
.newParent .newChild {
  color: white;
}
Run Code Online (Sandbox Code Playgroud)