With preprocessor variables it's easy to set up one variable and manipulate it so that I can use it to set multiple properties. (demo)
While experimenting with native css variables, I noticed that I could combine them with preprocessor variables, so in the following example: (use firefox)
h1 {
--length: 40px;
@length: var(--length);
line-height: @length;
border: 5px solid tomato;
}
line-height was correctly rendered at 40px
But, when I tried to manipulate the preprocessor variable - like this:
h1 {
--length: 40px;
@length: var(--length);
@length2: @length*2;
line-height: @length;
padding: @length2;
border: 5px solid tomato;
}
... the code failed.
Is this possible somehow?
As mentioned in my comment, my understanding of CSS variables is that the variable is resolved into its actual value by the UA. This happens after the Less compiler compiles the file and thus it wouldn't be aware of what is the actual value contained by the CSS variable.
To the compiler, the value of @length
is only var(--length)
. Since this is not a number, an error is thrown during compilation indicating that the math operation is being done on an invalid type.
OperationError: Operation on an invalid type on line 4, column 3:
One way to fix this would be to make the Less compiler output the variable name as it is and have the multiplier appended to it (like string concatenation). This would then leave the control to the UA.
But since all CSS math operations have to be given within calc()
function, the entire thing has to be wrapped within it. So, the below code would work fine.
h1 {
--length: 40px;
@length: var(--length);
@length2: ~"calc(@{length} * 2)";
line-height: @length;
padding: @length2;
border: 5px solid tomato;
}
Or, even the below would be enough if --strict-math
is enabled during compilation:
h1 {
--length: 40px;
@length: var(--length);
@length2: calc(@length * 2);
line-height: @length;
padding: @length2;
border: 5px solid tomato;
}
Above code when compiled produces an output similar to the one in Example 11 of the specs and so it should be a reasonably good way of doing this :)
... 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...