How to change image on hover with CSS
Topic: HTML / CSSPrev|Next
Answer: Use the CSS background-image
property
You can simply use the CSS background-image
property in combination with the :hover
pseudo-class to replace or change the image on mouseover.
Let's try out the following example to understand how it basically works:
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change Image on Hover in CSS</title>
<style>
.card {
width: 130px;
height: 195px;
background: url("images/card-back.jpg") no-repeat;
display: inline-block;
}
.card:hover {
background: url("images/card-front.jpg") no-repeat;
}
</style>
</head>
<body>
<div class="card"></div>
</body>
</html>
You can also combine the images into image sprite for smooth hover effect. However, if you want to achieve this effect using the <img>
tag you can use the CSS positioning method, like this:
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Image Swap on Hover with CSS</title>
<style>
.card {
width: 130px;
height: 195px;
position: relative;
display: inline-block;
}
.card .img-top {
display: none;
position: absolute;
top: 0;
left: 0;
z-index: 99;
}
.card:hover .img-top {
display: inline;
}
</style>
</head>
<body>
<div class="card">
<img src="images/card-back.jpg" alt="Card Back">
<img src="images/card-front.jpg" class="img-top" alt="Card Front">
</div>
</body>
</html>
Related FAQ
Here are some more FAQ related to this topic: