How to change image on hover with CSS?

How to change image on hover with CSS?

Asked on October 31, 2018 in HTML / CSS.
Add Comment


  • 1 Answer(s)

         CSS background-image Property is used for changing image on hover
    CSS background-image property in combination with the :hover pseudo class to change the image on mouseover.

    For example:

    <!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>
    

    The images can be combined into image sprite for smooth hover effect.
    So, For achieving this effect by using the <img> tag you can use the CSS positioning method,

    For example:

    <!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>
    
    Answered on October 31, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.