Is it possible for URLs in CSS Custom Properties to be relative to the CSS file where they are defined?

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?

Answer №1

An issue arises when the initial value for <url> is set to none, which is not valid. Chrome's console will point out this issue in the "Issues" tab, but it can be easily missed. In Safari, the error remains silent, however, in JavaScript, the error message is clear:

CSS.registerProperty({
  name: "--img",
  syntax: "<url>",
  inherits: true,
  initialValue: "none",
});
// This code will throw an error in both Chrome and Safari (but with different messages)
// indicating that the initial value provided does not match the specified syntax.

When the property registration fails and a url() function is used, the URL is only resolved when the variable is actually utilized as a <url> in the user's stylesheet. The URL then becomes relative to their stylesheet.

If the property is registered correctly using a valid url() as the initial value, the URL would be resolved at the time of definition, relative to the stylesheet in which the definition was made.

For example, you could have set

@property --img {
  syntax: "<url>";
  initial-value: url();
  inherits: true;
}

The specifications include a complete example demonstrating this behavior:

Ps: For more information on a related issue, you may want to check out this GitHub thread.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why aren't my messages showing up once I exit the textbox on my website?

After writing various functions to compare two passwords, I encountered an issue. My goal was for the message "The passwords match" or "Please enter your password again because the two passwords don't match" to be displayed when clicking out of the "v ...

Expand the column to occupy the remaining height of the row

I've been on the hunt for a solution to this issue, but I haven't had any luck finding one. Various flexbox properties like flex-grow: 1; and align-self: stretch; have been attempted, but none seem to achieve the desired outcome. The goal is to ...

What is the reason why boolean attributes dont actually have a boolean value in HTML?

It's interesting that certain elements have boolean attributes. I find it curious why the values are not true/false or 1/0. Is there a specific reason for this design choice? <option selected="selected">Ham Burger</option> or <input ...

What could be causing my custom cursor to malfunction?

I've been attempting to customize the cursor image, but despite following all provided instructions, it's still not working: CSS: body, html { margin: 0px; padding: 0px; border: 1px solid red; cursor: url(images/rsz_red_crosshair.gi ...

Is there a way to send emails with subject lines containing special characters?

I am facing an issue where, when I send an email with the subject containing "Ç", it displays as "?". I have tried various implementations to fix this such as using -charset="ascii", -charset=UTF-8, and modifying the subject line with different encodings. ...

Guide to retrieving IDs of images on a canvas during drag and drop functionality

I've developed a finite state machine drawing tool that includes drag-and-drop functionality for different images, such as states and arrows. Each arrow creates a div tag for the transition, with unique ids assigned to every state, arrow, and transiti ...

Removing outlines on <p> <a> or <div> elements with Ionic and Angular seems to be a challenging task

Hey there, I’m currently working on my application which includes a login page. I've implemented a “Forgotten password ?” link, but no matter what I try, like using .class and :focus {outline: none}, I still see a yellow square around the item. ...

Navigating Up a Directory with JQuery

Is there a way to navigate up one directory level in my jQuery code? The code below is referencing a folder named "uploads" on the C drive, but I can't find any mention of "uploads" in my HTML. How does it know to look there? And how can I go back to ...

Specify the height of a div tag based on a certain condition

I'm trying to style a div tag in a specific way: If the content inside the div is less than 100px, I want the div tag's height to be exactly 100px. However, if the content's height exceeds 100px, I want the div tag's height to adjust au ...

Issue with Bootstrap dropdown menu not showing up/functioning

I've spent the entire day trying to find a solution and experimenting with various methods, but I'm still unable to get it to work. The navbar-toggle (hamburger menu) shows up when the window is resized, but clicking on the button doesn't di ...

A guide to accessing the sibling of each selector with jQuery

Imagine you have the following HTML structure: <div class="parent"> <div class="child"></div> <div class="sibling">content...</div> </div> <div class="parent"> <div class="child"></div> <div ...

Adjusting the size of a Checkbox with CSS

Adjust the width of the checkbox for the call field to 25 pixels, ensuring it is displayed only when the left margin is clear. I'm having trouble figuring this out, even though it's probably something simple again. I double-checked that my style ...

Framework designed to be compatible with Internet Explorer 7 for seamless

Is there a CSS framework that provides full support for IE7 without any issues? Specifically, something similar to Twitter Bootstrap but with guaranteed rounded corners and properly functioning tabs. I have experienced problems with the Popover plugin sp ...

Completing a form with editable content - using PHP and HTML

I've browsed through numerous questions here, but I haven't found a solution that works for me. Here are the instructions I'm working with: $query = "SELECT nazwa,rok_prod,wypornosc FROM statek where id_statek=$id"; $wynik = pg_query($query ...

Implementing functionality: Removing a row and applying a CSS class upon button click

Check out the fiddle below: https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/ I need help with creating a remove function and adding a CSS class to a clicked row. 1. When I click on "remove", the clicked row should be deleted. When I click on a row, ...

Issue with QuickSand Script not displaying properly on Internet Explorer 7

My website features an edited version of Quicksand that displays correctly on Chrome, Opera, and Firefox, but runs into CSS issues on IE. Oddly enough, when I was using the static version, the CSS displayed properly even on IE until I added the Quicksand e ...

Margin in Bootstrap Panel Not Set to 0 as Needed

My bootstrap panel's margins are set to 0, but it doesn't seem to actually be 0. In the image attached, the margin shows as "-", which I assume means 0. However, when I highlight it, I see a large block of orange. Does this indicate that the marg ...

Storing user feedback in database using ajax

I have encountered a common issue in this thread, and although it has been discussed multiple times, I am still unable to solve my problem. My struggle lies in sending and fetching data from comment.php to insert.php. Below is the code from my comment.php ...

Elevation on Tab button from the upper side

On my website, I have a large form where pressing the tab key switches between input fields. The inputs will also jump to the top if we reach the bottom of the form. The issue is that I have a fixed header at the top, covering the first 60px. Is there a w ...

How can I link an HTML anchor to a calendar?

Is there a way to create a universal link that generates a calendar event using HTML? For example, we can create an email link with <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff9e9b9b8d9a8c8cbf9a879e928f9 ...