Mr White
Mr White

Reputation: 19

Replacing <img src> via pure CSS

Firstly, thanks in advance, I've been trying to figure this out for hours now and I just can't work it out..

I don't have access to the backend PHP / HTML but I want to change a few images in a sites design..

How can I change these images by pure CSS alone ? Is this even possible ?

<a href="example.php?action=task1" class="tooltip" title="task1">
<img src="/example/1/image1.png" alt="RP"></a>

<a href="example.php?action=task2" class="tooltip" title="task2">
<img src="/example/1/image2.png" alt="RP"></a>

Upvotes: 1

Views: 228

Answers (3)

Temani Afif
Temani Afif

Reputation: 272919

You can do like below using content applied to image and an attribute selector to identify each one:

img[src*="image1.png"] {
 content:url(https://picsum.photos/id/10/200/300);
}

img[src*="image2.png"] {
 content:url(https://picsum.photos/id/15/250/400);
}
<a href="example.php?action=task1" class="tooltip" title="task1">
<img src="/example/1/image1.png" alt="RP"></a>

<a href="example.php?action=task2" class="tooltip" title="task2">
<img src="/example/1/image2.png" alt="RP"></a>

Upvotes: 1

admcfajn
admcfajn

Reputation: 2082

You could add a pseudo-element after the images. I know of a couple places where psuedo-elements aren't allowed (like on form elements), but on the images or the links that wrap them you could use something like the following

img { position: relative; display: block; width: 350px; height: 150px;  }
img:after { 
  content: '';
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url( 'https://via.placeholder.com/350x150' )
}
<img src="/example/1/image1.png" alt="RP">

The biggest thing to remember (for me at least) is the content attribute is required for :before & :after psuedo-elements

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76574

No, you cannot change the src attribute via CSS, because the src attribute is an HTML attribute, outside the scope of CSS styling. But:

background-image

If you want a pure CSS solution, then you can place divs instead of img, possibly wrapping the divs around the anchors.

<div style="width: 100px; height: 100px; background-image: /example/1/image1.png;"><a href="example.php?action=task1" class="tooltip" title="task1"></div>

See an example here: https://www.w3schools.com/cssref/pr_background-image.asp

I know you do not have access to HTML development, but if you will have access, then it's worth knowing that it can be solved this way.

Javascript

With Javascript you can easily sun something like:

var images = document.getElementsByTagName("img");
for (let image of images) {
    //Do something with image.src
}

Upvotes: 1

Related Questions