让我们来考虑一下LESS编译的方式。如果您愿意,可以在
https://fiddlesalad.com/less编辑器中运行任何一个示例。
这个例子中,我只是包含了一些任意颜色和一个“background”属性,以便更容易理解。当您导入base.less时,在您的文件中实际上只是加入了一些LESS规则。因此,为了澄清,如果我们“扩展”您的导入,编译成CSS之前,该文件可能如下所示:
.some-css-class{
@color1: red;
background: @color1;
}
.some-css-class {
@color1: purple;
}
这个输出结果是什么?
.some-css-class {
background: red;
}
为什么?你可能会说“我已经重新声明了颜色变量,难道它不应该重新编译规则吗?”然而,这并非LESS的设计原则——它是与CSS向后兼容的,因此必须在后面出现规则才能覆盖前面的规则。取而代之的是,看下面这个例子:
.some-css-class{
@color1: red;
background: @color1;
}
.some-css-class {
@color1: purple;
background: @color1;
}
以下是当前的输出结果:
.some-css-class {
background: red;
}
.some-css-class {
background: purple;
}
规则被分成两个输出,因为第二个规则在层叠中发生得更晚,所以它具有更高的优先级 - 除非该类不存在于其他地方,否则“紫色”规则将优先采用。
在LESS中,“懒加载”变量-它将始终使用从内部作用域开始找到的最后一个值。因此:
.some-css-class {
@color1: purple;
background: @color1;
@color1: blue;
}
将输出:
.some-css-class {
background: blue;
}
不幸的是,如果我们试图将您之前的规则作为mixin扩展,它会在将它们引入新类之前从每个类中解析值:
.some-css-class{
@color1: red;
background: @color1;
}
.some-css-class {
@color1: purple;
background: @color1;
@color1: blue;
}
.another-css-class {
.some-css-class();
@color1: orange;
}
输出:
.some-css-class {
background: red;
}
.some-css-class {
background: blue;
}
.another-css-class {
background: red;
background: blue;
}
因此,“覆盖”这些值的理想方式是将原始规则集转换为参数化mixin:
.some-css-class(@color1, @color2) {
background: @color1;
color: @color2;
}
.another-css-class {
.some-css-class(red, blue);
}
最终,你的输出将是这样的:
.another-css-class {
background: red;
color: blue;
}
编辑:最终我建议您将原始规则从文件中复制出来(而不修改该文件),并将其更改为您版本中的mixin。最终,您将获得与扩展和覆盖新类别的变量相同的CSS净量。
.some-css-class
代码的人决定您不需要它)。无论如何,这看起来像一个XY问题(即,您实际问题的解决方案可能取决于为什么您需要覆盖这些变量)。 - seven-phases-max