Can I Interpolate CSS Variables Within a URL Expression?
In CSS, custom properties (also known as CSS variables) provide a convenient way to store and modify values programmatically. However, users may encounter limitations when attempting to interpolate variable values within the URL function, such as in the background property.
Example:
:root { --url: "https://download.unsplash.com/photo-1420708392410-3c593b80d416"; } body { background: url(var(--url)); }
Unfortunately, such interpolation is not possible within the url() function due to legacy reasons. CSS parsers treat url(var(--url)) not as separate tokens, but as a single invalid url() token.
Despite interpolation being commonly available for CSS functions like rgba(), it's not permitted for url() due to potential ambiguities and parsing issues.
Therefore, explicitly defining the entire URL string within the custom property is necessary:
:root { --url: url("https://download.unsplash.com/photo-1420708392410-3c593b80d416"); } body { background: var(--url); }
Alternatively, JavaScript can be used to accomplish the desired interpolation.
The above is the detailed content of Can I Use CSS Variables Inside a `url()` Function?. For more information, please follow other related articles on the PHP Chinese website!