CSS - LESS类继承

15

我正在使用Twitter Bootstrap的样式,并且对继承有疑问。

我想创建两个标签类,它们可以继承Bootstrap中的标签样式。

.label-new {
    .label; .label-important;
}
.label-updated {
    .label; .label-warning;
}

然而,上述代码将导致LESS解析错误"NameError: .label-important未定义",因为.bootstrap中使用以下方式定义了.label-important和.label-warning:

.label,
.badge {
  // Important (red)
  &-important         { background-color: @errorText; }
  &-important[href]   { background-color: darken(@errorText, 10%); }
  // Warnings (orange)
  &-warning           { background-color: @orange; }
  &-warning[href]     { background-color: darken(@orange, 10%); }
}

是否有特殊的语法可以继承.label-important/warning样式?

提前致谢。


我相信在你的两个新类中_仅仅_混合.label将会给你.lable-new-important.label-new-warning(等等)。我猜你只想要newimportant属性和updatedwarning属性,这是你的目标吗? - ScottS
是的,没错。我宁愿不像下面建议的那样重新定义颜色。所以看来这是 LESS 的一个限制,很遗憾。 - Cat
是的,这似乎是一个有用的功能。如果您不想在两个地方定义颜色,我已经添加了另一个建议。这是我唯一的两个建议。 - ScottS
1个回答

11
我认为你只能继承 .label,这应该会给出 .label-new-important.label-new-warning(以及相应的 updated)。如果这不是你想要的,并且你想要新添加的扩展,你可能需要直接重新定义 .label 的颜色来隔离并定义你想要的内容。像这样:
.label { 
  // New (red) 
  &-new           { background-color: @errorText; } 
  &-new[href]     { background-color: darken(@errorText, 10%); } 
  // Updated (orange) 
  &-updated       { background-color: @orange; } 
  &-updated[href] { background-color: darken(@orange, 10%); } 
} 

编辑(如果您不想重新定义颜色而使用混合)

要避免重新定义颜色,您需要更改原始定义,并执行以下操作:

首先,删除原始的.label.badge定义,然后其次,像这样更明确地定义它们:

.label-important,
.badge-important {
  // Important (red)
  { background-color: @errorText; }
  { background-color: darken(@errorText, 10%); }
}

.label-warning,
.badge-warning {
  // Warnings (orange)
  { background-color: @orange; }
  { background-color: darken(@orange, 10%); }
}

.label-new {
    .label-important;
}

.label-updated {
    .label-warning;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接