Handling optional custom property values in multi-valued CSS properties such as transform
requires sometimes some tricks. Suppose you have an element whose transform
attribute contains multiple values:
.el { transform: translate(100px) scale(1.5) skew(5deg); }
If you want to apply only certain transform values as needed, you can use custom properties to achieve optionality:
.el { /* |-- default ---| |-- optional --| */ transform: translate(100px) var(--transform); }
However, if --transform
is not defined, the entire transform
property will be invalid. The solution is to use a null value as the fallback value:
.el { transform: translate(100px) var(--transform, ); }
Pay attention to the difference? Here a null value ( ,
) is defined as a fallback. According to the specification:
Unlike the usual comma omission rule (which requires omitting when commas do not separate values), in
var()
, a separate comma (nothing afterwards) must be considered valid, indicating an empty fallback value.
This is similar to the CSS custom property switching technique, which utilizes custom properties to have space values.
This trick works with any multi-valued CSS attribute. In addition to transform
, the following demonstration also uses text-shadow
, background
, and filter
.
For some properties that accept multiple values (such as text-shadow
), special handling is required since they only apply to comma separators. In these cases, when defining a CSS custom property, you (as the code author) know that it is only used in the context of the custom property's defined value. Then you should insert a comma directly before the first value in the custom property, like so:
--text-shadow: ,0 0 5px black;
Of course, this limits the ability to use this variable if the attribute value is unique. However, this can be solved by creating a "layer" of variables, i.e. custom properties point to a lower level custom properties.
While exploring this trick, I found that there is a bug in the Sass compiler that removes empty fallback values ( ,
), which is not consistent with the specification. I've reported this error and hope it will be fixed soon.
As a temporary workaround, you can use fallback values that do not cause rendering, for example:
transform: translate(100px) var(--transform, scale(1));
The above is the detailed content of Neat Optional Custom Property Values Trick. For more information, please follow other related articles on the PHP Chinese website!