Home > Web Front-end > CSS Tutorial > Can I Use CSS Variables Inside a `url()` Function?

Can I Use CSS Variables Inside a `url()` Function?

Mary-Kate Olsen
Release: 2024-12-09 21:47:10
Original
883 people have browsed it

Can I Use CSS Variables Inside a `url()` Function?

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));
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template