How to change image on hover with CSS

Topic: HTML / CSS« Prev|Next »

Answer: Use the CSS background-image Property

You can use the CSS background-image property in combination with the :hover pseudo class to change the image on mouseover, like this:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <title>Change Image on Hover in CSS</title>
  • <style type="text/css">
  •     .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 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:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <title>Image Swap on Hover with CSS</title>
  • <style type="text/css">
  •     .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:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.