LAST UPDATED: AUGUST 5, 2021
How to change image on hover with CSS?
The CSS hover effects give us the ability to change the CSS property. The image can also be changed using the hover on CSS. In this tutorial, we will learn to change the image on hover.
CSS background-image property
The CSS background-image
along with :hover
pseudo-class is used to change the image on hover. Add the image using the background-image class and add another image to the :hover
pseudo-class. In addition to that, we can also set the width and height of the image.
Example: Program to change the image on hover using CSS property
Here is a program to illustrate the hover effect.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
</head>
<style>
.change {
height: 200px;
width: 300px;
background-image: url("https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1626415729-101156.png") ;
background-repeat: no-repeat;
}
.change:hover {
background-image: url("https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1626415784-101156.png") ;
background-repeat: no-repeat;
}
</style>
<body>
<h2> Change image on hover</h2>
<div class="change"></div>
</body>
</html>
Output:
Before hovering
On hovering
Example: Change image using the display Property
Here in the example, we have added two images within the <a> tag then we have hidden the second image by adding display: none
property to it. So before hover, the first image appears. Further, we have added display: block
property to the second image and display: none
to the first image to the :hover
pseudo class. So on hover, the first image disappears and the second image appears.
Conclusion
So, here we have learned to easily change images on hover just using some properties of CSS. We have illustrated it with examples. So now you don't need to worry about adding javascript to change the image on hover.