Let’s say, in style.css, I need to append a query string ?version=2 after the url of a background image for force-reloading:
background-image: url(sprite.svg?version=2#icon-pencil);
Because the background image will be used through out the CSS file, I thought it’s better to turn the query string into a CSS variable var(--sprite-query-string) like the following example. But unfortunately it doesn’t work at all:
background-image: url(sprite.svgvar(--sprite-query-string)#icon-pencil);
Therefore, I have to resort to PHP variable. I turned style.css into a PHP file style.php. The defining of the PHP variable and the stylesheet reference in HTML are like:
<?php
$sprite_query_string = '?version=2';
?>
<link rel="stylesheet" href="style.php?sprite_query_string=<?php echo urlencode($sprite_query_string); ?>">
And then in style.php, I can use the PHP variable as many times as I like:
<?php header('Content-type: text/css; charset=UTF-8'); ?>
.icon-pencil {
background-image: url(sprite.svg<?php echo $_GET['sprite_query_string']; ?>#icon-pencil);
}
.icon-star {
background-image: url(sprite.svg<?php echo $_GET['sprite_query_string']; ?>#icon-star);
}
.icon-heart {
background-image: url(sprite.svg<?php echo $_GET['sprite_query_string']; ?>#icon-heart);
}
But that brings up another issue: style.php cannot be cached by browsers by default.
So my question is: how to make style.php cacheable and also easily force-reloadable? For example, after I added more CSS code into style.php, I want an easy way to force visitors to reload style.php, such as appending a parameter timestamp=20250405 after style.php’s query string:
<link rel="stylesheet" href="style.php?sprite_query_string=<?php echo urlencode($sprite_query_string); ?>×tamp=20250405">