Hover over the below image to change the images:
There are several methods that we can use to change images on hover. In this article, we are going to learn the two most commonly used methods which we can use to swap images on hover.
These two methods are as follows:
Let’s look at both methods in detail.
Change Image on Hover using the background-image Property
The basic idea of this method is to set the first image as a background image of a div element and then replace it with the second image when we hover over it simply by changing its URL.
To set an image as a background image of an element we use the background-image property and to add the hover effect we have to use the :hover
pseudo-class.
Here is the full example:
Example:
.container{ background-image: url(images/coffee.jpg); /* First Image URL */ background-size: cover; background-repeat: no-repeat; width: 250px; height: 250px; border: 2px solid red; transition: 0.5s ease; } .container:hover{ background-image: url(images/berry.jpg); /* Second Image URL */ }
Change Image on Hover using the display Property
In this method, we put the two images inside a div container and show only of one them at a time. That is, we display the first image by default and keep the second image hidden by setting the display property to none
.
And when we hover over the container, we display the second image on the top of the first image simply by setting the display property to inline
and setting its z-index to a higher value such as 99 or 999.
But only specifying the z-index and display property isn’t enough for this approach. Because we have to place the two images on top of each other.
To do this, we have to set the div container’s position to relative
and that of the images to absolute
so that we can place both the images at the same position using the top, left, bottom and right properties.
Here is the full example:
Example:
.container{ width: 250px; height: 250px; border: 2px solid red; position: relative; } .container img{ width: 100%; position: absolute; left: 0px; top: 0px; } .img-top{ display: none; /* Hide top Image */ z-index: 99; } .container:hover .img-top{ display: inline; /* Show top Image */ }