I have a CSS library with resources like images and fonts that can be accessed from anywhere via CDN. I am trying to create URLs for these resources as Custom CSS Properties, relative to the library.
<!-- https://my.server/index.html -->
<link rel="stylesheet" href="https://my.cdn/a/lib.css">
<div style="background-image: var(--img)"></div>
/* https://my.cdn/a/lib.css */
@property --img {
syntax: "<url>";
initial-value: none;
inherits: true;
}
:root {
--img: url(./img.svg);
}
<!-- https://my.cdn/a/img.svg -->
<svg xmlns="http://www.w3.org/2000/svg">
<!-- […] -->
</svg>
The goal is to dynamically set the background-image URL of the div
element without directly referencing it, since --img
may point to different URLs at times. The URL should always be relative to the document (i.e. ) or even relative to the stylesheet using the CSS Custom Property. For example,
/* https://my.server/b/lib.css */
@import url("https://my.cdn/a/lib.css");
div {
background-image: var(--img);
}
This would effectively link to .
One workaround involves creating CSS classes in a/lib.css
that apply the CSS Custom Properties:
/* https://my.cdn/a/lib.css */
/* […] */
.img--background-image {
background-image: var(--img);
}
To use this workaround, consumers simply apply the class to their HTML elements:
<!-- https://my.server/index.html -->
<link rel="stylesheet" href="https://my.cdn/a/lib.css">
<div class="img--background-image"></div>
However, this approach has limitations in terms of flexibility and requires manual HTML adjustments.
In my previous attempt using @property
when Chrome first implemented it, the URL resolution worked correctly. Unfortunately, this is no longer the case today.
Has anyone faced a similar challenge? How did you resolve it? Am I overlooking a simple solution?