Home > Software engineering >  Setting image root URL as a CSS variable and using CSS content
Setting image root URL as a CSS variable and using CSS content

Time:05-04

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.

CodePudding user response:

You cannot use the content property for this. In your case you should use your backend language or javascript to do this. Example in php:

base.php

define(IMAGE_BASE_URL, 'https://examplesite.com');

index.php

<img src="<?= IMAGE_BASE_URL ?>/dir/file.png" />

So in all files that have images you include the base file.

CodePudding user response:

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>
  • Related