-
Notifications
You must be signed in to change notification settings - Fork 779
Description
Current Situation
Code like the following does not work:
div
{
--size: 2px;
width: calc(1px * pow(var(--size), 2));
}This is because the --size variable is declared as a length value, not a bare decimal value (see https://stackoverflow.com/questions/79894255/why-do-css-functions-like-pow-not-work-in-browsers).
Desired Situation
It is desirable to use "typed" values for variables instead of simple decimal numbers so that they have semantics. Moreover, the unit information is important, as using a different unit can dramatically change the design.
CSS mathematical expressions, however, don't accept length or percentage values. They require bare decimal values.
Improvement Suggestion
To keep things concise and to avoid introducing breaking changes, I propose to add two new conversion functions to the CSS spec (one with an overload).
| Function name | Description |
|---|---|
v(arg) |
Returns the decimal value from the specified argument unit value. |
u(arg) |
Replaces the decimal number value from the specified argument unit value with a 1 and returns the unit identity value. |
u(arg1, arg2) |
Replaces the decimal number value from the specified first argument unit value with the second argument decimal number and returns the corresponding unit value. |
Synopsis
- The proposed conversion functions will be used quite often, so their name should be short (
u()andv()in this case).
Details
-
v(arg)
-
v(arg)takes a single argument.- The single argument may be any decimal number value with optional unit.
- The
v(arg)function strips the unit and returns the decimal number value only. - If the argument is a decimal number without unit, the
v()function returns the decimal number without change.
-
u(arg)
-
u(arg)takes a single argument.- The single argument may be any CSS value with a unit.
- The
u(arg)function replaces the decimal number with the constant value1and returns the typed identity unit value.
-
u(arg1, arg2)
-
u(arg1, arg2)takes two arguments.- The first argument may be any CSS value with a unit.
- The second argument may be any CSS value; either a decimal number or a value with a unit.
- The
u(arg1, arg2)function replaces the decimal number from the first argument with the decimal value from the second argument and returns the typed unit value with the decimal value from the second and the unit from the first argument.
Examples
v(23px)returns23v(5%)returns5v(45deg)returns45v(789)returns789
u(23px)returns1pxu(1rem)returns1remu(0%)returns1%u(-45deg)returns1deg
u(23px, 5)returns5pxu(1rem, 25px)returns25remu(0%, 111deg)returns111%u(-45deg, -123)returns-123deg
Result
Using the proposed two new conversion functions, the above described problem could be solved like this:
A
div
{
--size: 2px;
width: calc(u(var(--size)) * pow(v(var(--size)), 2));
}B
div
{
--size: 2px;
width: u(pow(v(var(--size)), 2), var(--size));
}