如何使用 LESS 合并父子样式属性

How to merge parent and child style properties using LESS

我有更少的代码,这工作得很好。我只是想在less cli编译的时候节省一些空间。

.secondary-content {
    background: #ffcc80;
    color: white !important;

    label, i {
        background: #ffcc80;
        color: white !important;
    }
}

当我从命令提示符 运行 less 时,输出如下所示。

.secondary-content {
  background: #ffcc80;
  color: white !important;
}
.secondary-content label,
.secondary-content i {
  background: #ffcc80;
  color: white !important;
}

如您所见,它们在每个块上都是分​​开的。我想让他们在同一个街区。我怎样才能轻松合并父子样式属性?像这样。

.secondary-content,
.secondary-content label,
.secondary-content i {
  background: #ffcc80;
  color: white !important;
}

我学的还少,所以任何帮助将不胜感激。

提前致谢

您可以像下面的代码片段一样使用 parent selector (&)。使用父选择器意味着相同的规则适用于 .ghost .secondary-content 选择器及其子 labeli 标签。

.ghost .secondary-content {
    &, label, i {
        background: #ffcc80;
        color: white !important;
    }
}

@Harry 提供的解决方案当然有效。当你学习 Less 时,你应该记住,Less 可以帮助你编写 CSS 代码干而且更有效率。 Less 不帮助你解决问题,你不能解决共同 CSS,Less 编译成 CSS 并且不向编译的 CSS 添加任何功能。

要减少共享某些属性的选择器的 CSS 大小,您应该考虑 Less 的扩展功能:http://lesscss.org/features/#extend-feature-reducing-css-size:

.selector1 {
  color: red;
}

.selector2:extend(.selector1) {}

输出:

.selector1,
.selector2 {
  color: red;
}

要解决您的问题,您应该重新考虑所需的 CSS 代码,而不是 Less 代码。 labeli嵌套不能使用extend,但为什么要嵌套设置colorbackground-color

background-color 的默认值是 transparent 所以当你为父元素设置 background-color 时你没有为子元素设置 background-color (当使用相同的值时)。

您可以使用其他具有更高特异性的样式规则覆盖默认值 transparent,另请参阅 http://www.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/

一个给你的嵌套 label 错误的例子 background-color:

label {
background-color:green;
}             
.secondary-content {
background-color:red;
color: white;    
} 

color 属性 相同,它始终从其父级继承,除非应用于锚点。

您也在使用!important,请参阅:https://css-tricks.com/when-using-important-is-the-right-choice/