使用预处理器变量可以很容易地设置一个变量并对其进行操作,这样我就可以使用它来设置多个属性。 ( demo )
在试验 native css variables 时, 我注意到我可以将它们与预处理器变量结合起来,所以在 the following example 中: (使用火狐)
h1 {
--length: 40px;
@length: var(--length);
line-height: @length;
border: 5px solid tomato;
}
行高正确呈现为 40 像素
但是,当我试图操纵预处理器变量时 - like this :
h1 {
--length: 40px;
@length: var(--length);
@length2: @length*2;
line-height: @length;
padding: @length2;
border: 5px solid tomato;
}
...代码失败。
这有可能吗?
最佳答案
正如我在评论中提到的,我对 CSS 变量的理解是,变量由 UA 解析为其实际值。这发生在 Less 编译器编译文件之后,因此它不知道 CSS 变量包含的实际值是什么。
对于编译器来说,@length
的值只是var(--length)
。由于这不是一个数字,编译期间会抛出一个错误,表明正在对无效类型进行数学运算。
OperationError: Operation on an invalid type on line 4, column 3:
解决此问题的一种方法是让 Less 编译器按原样输出变量名,并在其后附加乘数(如字符串连接)。然后,这会将控制权交给 UA。
但由于所有 CSS 数学运算都必须在 calc()
函数中给出,所以整个东西都必须包含在其中。因此,下面的代码可以正常工作。
h1 {
--length: 40px;
@length: var(--length);
@length2: ~"calc(@{length} * 2)";
line-height: @length;
padding: @length2;
border: 5px solid tomato;
}
或者,如果在编译期间启用了 --strict-math
,那么即使下面的内容也足够了:
h1 {
--length: 40px;
@length: var(--length);
@length2: calc(@length * 2);
line-height: @length;
padding: @length2;
border: 5px solid tomato;
}
上面的代码在编译时会产生类似于 Example 11 of the specs 中的输出所以这应该是一个相当好的方法:)
... Note, though, that
calc()
can be used to validly achieve the same thing, like so:.foo { --gap: 20; margin-top: calc(var(--gap) * 1px); }
var() functions are substituted at computed-value time...
关于less - 是否可以使用 LESS 操作 css 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35723642/