Suthan Bala
Suthan Bala

Reputation: 3299

Changing Img Src to parent A href Using CSS

Is it possible to change the img element to its parent a tag's href attribute? For example, if I have:

<a class="img-parent" href="http://placehold.it/400x200">
    <img class="img-class" src="http://placehold.it/90x90" alt="This will change" />
</a>

Can I change the content of the img using only CSS?

I know for a fact that I can change the img using the following code, but can I just point it to the parent's href attribute?

.img-class{
   content:url("http://placehold.it/400x200");
}

Upvotes: 2

Views: 321

Answers (1)

Oriol
Oriol

Reputation: 288590

Theoretically, I think you could use CSS variables:

.img-parent {
  --img: attr(href);
}
.img-class {
  content: url(var(--img));
}

But don't expect it to work (yet):

  • content applying to all elements (and not only ::before and ::after) is not widely implemented.
  • attr() in properties other than content is not widely implemented.
  • CSS variables are not widely implemented.
  • CSS variables inside url() are even less implemented.

Upvotes: 2

Related Questions