Q:

How to change image on hover with CSS

0

How to change image on hover with CSS

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

<!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("/examples/images/card-back.jpg") no-repeat;
        margin: 50px;
    }
    .card:hover {
        background: url("/examples/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:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Change Image on Hover in CSS</title>
<style>
    .card {
        width: 130px;
        height: 195px;
        position: relative;
        display: inline-block;
        margin: 50px;
    }
    .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="/examples/images/card-back.jpg" alt="Card Back">
        <img src="/examples/images/card-front.jpg" class="img-top" alt="Card Front">
    </div>
</body>
</html>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

HTML / CSS Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to position text over an image using CSS... >>
<< How to place border inside of a div element using ...