How to Change Image on Hover with CSS
To change the background image on an element in CSS on hover we can use the CSS pseudo :hover
class to set a new background property.
Create an Element with a Class
First, let's create an HTML div element with a class
attribute.
<div class="picture"></div>
Now let's create the CSS that will give the element a background image and change the background on a hover event.
.picture {
width: 600px;
height: 600px;
background: url('cat.jpg') no-repeat;
background-size: contain;
}
.picture:hover {
background: url('cat_hover.jpg') no-repeat;
background-size: contain;
}
Change HTML img Tag Background with CSS
If you want to use HTML img
tags and change the image on hover using CSS we will have to use two img
tags and the position: absolute
CSS property.
<div class="picture">
<img src="cat.jpg" alt="cat 1">
<img src="cat_hover.jpg" alt="cat 2" class="hover">
</div>
.picture {
position: relative;
}
.picture img {
width: 600px;
height: 600px;
position: absolute;
top: 0;
left: 0;
}
.picture .hover {
display: none;
}
.picture:hover .hover {
display: block;
}
In the above example, we have a div
containing the two img
tags; the one with the hover
class has display: none
applied to it. Both images are positioned absolutely at the top left of the container div
. On hover the second image is set to display, covering the first image.
Conclusion
You now know how to display an image on hover when the background image is in the HTML source or in the CSS.