Customized properties and CSS parsing are all the time good for surprises like !essential
behaving barely in a different way or properties being “invalid at computed worth time”.
At present I found yet one more shock — customized properties do not work together with the url()
perform. 😲
.one thing {
--image: "https://jo.com/picture.jpg";
background: url(var(--image));
}
Roman Dvornov describes the main points fairly effectively in a GitHub situation, however let me offer you a condensed rationalization.
Your url()
-containing CSS will likely be parsed in a different way, relying on how you utilize url()
. There’s an outdated and a more recent approach:
- Outdated:
url(https://jo
.com/picture .jpg) - Newer:
url('https://jo
or.com/picture .jpg') url("https://jo
.com/picture .jpg")
The issue of the legacy url()
token
And these lacking quotes of the outdated approach may look like a tiny element, however they have an effect on how your CSS is parsed.
With out quotes, the url()
syntax seems like a CSS perform, nevertheless it is not. CSS parsers will deal with it as a single token, a so-called url-token
.
.one thing {
background: url(https://ja.com/picture.jpg);
// ---------------------------/
// with out quotes this ☝️ is
// a single CSS token
}
And this complete token from url(
to the closing )
enforces parentheses, whitespace characters, single quotes (‘) and double quotes (“) to be escaped with a backslash.
url()
with a quoted string, then again, is a standard and versatile CSS perform notation, which is parsed half by half and works as anticipated.
However now, guess what occurs once you wish to use a customized property together with url()
?
.one thing {
--image: "https://jo.com/picture.jpg";
background: url(var(--image));
// ☝️ "No quotes? Cool, that is a url-token!"
// 😢 "Too unhealthy although, `(` is not allowed in right here..."
// ❌ "I will throw all the pieces away!"
}
As a result of there are not any quotes, this declaration is parsed as a url-token
. And sadly, the (
in var(--image)
is not escaped, so the parser throws an error and invalidates the whole CSS declaration.
And this legacy url-token
parsing is why you’ll be able to’t use customized variables within url()
.
What is the standard resolution, when there’s an issue with outdated internet legacy? It is inventing new stuff as a result of we won’t break the online and simply change issues.
To allow customized properties in url()
there is a new alias on the town. The src()
notation behaves the identical approach as url()
however with out this bizarre legacy url-token
logic.
.one thing {
--image: "https://jo.com/picture.jpg";
background: src(var(--image));
}
Drawback solved! However but, no browser helps src()
(I could not discover browser help data however examined present Chrome, Safari and Firefox), so it is time for us to attend. 🤷♂️
CSS parsing and customized properties — all the time good for a shock!
If you wish to learn extra about this subject, listed here are some assets: