是否可以用更少的时间扩展扩展属性?我在一个(分布式)文件中有定义,并且在我的特殊情况下需要将 !important
添加到现有属性。
例如,我有一个定义此类的 less 文件
.pfx-grey-light-bg {
background-color: #e5e5e7;
}
我现在想引用这个 less 文件,但将颜色扩展到重要
.pfx-metro-orange-dark-bg:extend(.pfx-orange-dark-bg){
//Pseudo code
//background-color: &extended.backgroundColor !important
}
结果应该是
.pfx-metro-grey-light-bg {
background-color: #e5e5e7 !important;
}
最佳答案
不,您不能以这种方式单独扩展单个属性。您可以扩展整个规则集,但扩展时,选择器将被合并,因此 !important
必须应用于两个选择器或不应用于任何选择器。
在您的情况下,属性值不同,因此选择器不能组合在一起。但是,如果 background-color
是原始类中您希望应用于派生类的唯一属性(或者)如果您希望将原始类的所有属性应用于派生类并将 !important
附加到所有这些,然后您可以使用以下内容。
.pfx-grey-light-bg {
background-color: #e5e5e7;
}
.pfx-metro-orange-dark-bg{
.pfx-grey-light-bg !important;
}
编译时,它将产生以下输出:
.pfx-grey-light-bg {
background-color: #e5e5e7;
}
.pfx-metro-orange-dark-bg {
background-color: #e5e5e7 !important;
}
或者,如果您的基类具有多个属性,并且您只想将 background-color
应用于派生类,那么您有以下三个选项:
选项 1:使用变量
@color: #e5e5e7;
.pfx-grey-light-bg {
background-color: @color;
color: #fff;
}
.pfx-metro-orange-dark-bg{
background-color: @color !important;
}
选项 2:编写一个虚拟 mixin 并按如下方式使用它。这不会在输出 CSS 中导致任何额外的代码行,因为 mixin 有括号,因此不会输出。
.dummy-mixin(){
background-color: #e5e5e7;
}
.pfx-grey-light-bg {
.dummy-mixin;
color: #fff;
}
.pfx-metro-orange-dark-bg{
.dummy-mixin !important;
padding: 10px;
}
选项 3:更复杂,使用 protected mixin 和可选的 @important
参数来决定是否附加 !important
。除非您有非常紧迫的需求,否则我不会推荐这样做。
.dummy-mixin(@color, @important: no){
& when (@important = no){
background-color: @color;
}
& when (@important = yes){
background-cokor: @color !important;
}
}
.pfx-grey-light-bg {
.dummy-mixin(#e5e5e7);
color: #fff;
}
.pfx-metro-orange-dark-bg{
.dummy-mixin(#e5e5e7; yes);
padding: 10px;
}
关于less - 可以更少地引用扩展属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28315498/