When the spec says...
Each property that allows percentages also defines the value to which the percentage refers.
... this definition is given by the spec, and then a conforming user agent implements the calculation according to the spec. The spec does not make any reference to user-defined percentage calculations. If I were to hazard a guess, it's probably because it's altering how a built-in CSS unit fundamentally works could potentially open developers up to a plethora of complications.
The calc()
function, introduced here in the same spec that you link to, by itself does not allow you to specify a CSS property, either of the same element or some other element, which means for example you can't do something like this:
.text {
height: 100px;
line-height: calc(100% * height);
}
However, there's a newly-published draft called CSS Custom Properties for Cascading Variables, which allows authors to specify custom property values and use them in arbitrary rulesets in a stylesheet. And while the module itself doesn't discuss a way for users to define how percentages should be calculated, it does discuss using cascading variables with calc()
.
This is very promising: since you're already able to perform multiplication and division with calc()
, you can fully emulate percentage calculations by multiplying by a decimal number instead of a percentage (or just use the cascaded value as is for 100%). You can even force properties that don't normally accept percentages, such as border-width
, to have their values calculated based on some other property using this method.
Here's an example, with an interactive proof-of-concept that works in Firefox 31 and later, where the current draft is implemented as of this writing:
.text {
--h: 50px;
height: var(--h);
/* 100% of height, given by --h
Line height percentages are normally based on font size */
line-height: var(--h);
/* 20% of height, given by --h
Border properties do not normally accept percentages */
border-width: calc(0.2 * var(--h));
border-style: solid;
}
The only caveat is that, because var()
only works with custom properties, you need to
- declare the value in its own custom property, and then
- any property that depends on this value must access the custom property through
var()
.
But the fact that it works is in itself very, very promising and we can only hope that this new module will continue to be developed and be more widely implemented.