'Setting image root URL as a CSS variable and using CSS content
I have a site with hundreds of pages and thousands of images, and we are likely to need to change the base URL from something like site_a.com to b_site.com, not once, but three to four times in the next year. I really don't want to have to go through all the image URLs on all the pages and change them manually more than once.
I was trying to use the CSS content feature, but it doesn't look like it does the right job, or I feel like I am just doing it wrong. The idea would be something like this:
:root {
--imgroot: url('https://imgs.xkcd.com/');
}
img {
content: var(--imgroot);
}
This way, when we DO change the base URL, all I need to do is change the URL listed in the root section to change it for all images across all the pages, and then the HTML would just be something like:
<p><img src="comics/2.png"></p>
When I try this, it looks like the content is only using the info from the --imgroot variable, and not picking up the comics/2.png. I'm not sure what to try next.
Solution 1:[1]
just put this line <base href="https://www.yourwebsite.com/" target="_blank"> in your html head tag, it also supports links in your HTML; try like below:
<head>
<base href="https://www.yourwebsite.com/" target="_blank">
</head>
<body>
<img src="images/stickman.gif" width="24" height="39" alt="Stickman">
<br>
<a href="blog/first-article">HTML base tag</a>
</body>
Solution 2:[2]
You cannot use the content property for this.
In your case you should use your backend language or javascript to do this.
Example in javascript:
base-url.js
document.querySelectorAll('img[data-base]').forEach(img => {
let base;
// Here you add the base urls you need
const baseOne = 'https://siteone.com';
const baseTwo = 'https://sitetwo.com';
switch (img.dataset.base) {
// Create a case for each of the above bases
case 'one':
base = baseOne;
break;
case 'two':
base = baseTwo;
break;
}
// Here the img[src] is replaced
img.setAttribute('src', base + img.getAttribute('src'));
});
So in your img tags you need to do this:
<img src="/dir/file.png" data-base="one" />
On every page that you need this functionality, add the base-url.js file at the bottom of the page, if not at the bottom of the page the script will not work because the <img /> tags have not yet been generated.
Remembering that the value of the data-base attribute of the images must be the same used in the case inside the switch.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ramin eghbalian |
| Solution 2 |
