Alex Alex - 3 months ago 6
CSS Question

Why does a different image source with CSS transition not work when hovered?

I have an

<a>
tag that I want to change the image source to another image source when I hover over it, while having the transition effect on the image as well. The transition works with a
background-image
property for a
<div>
tag, but not with the
content
property for an
<img>
tag.


So far this is what I have:


.topLogo {
height: 64px;
content: url(image1.png);
transition: 0.2s;
}
.topLogo:hover {
height: 64px;
content: url(image2.png);
}

Answer

I believe content: is for the content between tags. It wouldn't work for <img> beause there's no closing </img>.

There's no way to alter HTML attributes with CSS. You could use javascript/jquery. I have a feeling you don't want to though.

Since you're already using CSS to set the URL, why not use a blank <span> or <div> instead of an <img>?

<span class="topLogo"></span>

<style>
    .topLogo:before {
        height: 64px;
        content: url('image1.png');
        transition: 0.2s;
    }
    .topLogo:before:hover {
        height: 64px;
        content: url('image2.png');
    }
</style>