Change image source (src) on hover using CSS

In this post, we will see how to change images on hover using CSS.

We cannot change the <img> tag src (source) using CSS directly. For that, we have to use JavaScript function.

Check How to change image on hover using JavaScript.

However, we can swap or replace the <img> tag of the element using CSS.

To change image on hover with CSS:

  1. Use :hover selector to change the background-image property of a div.
  2. Change the display property of the <img> tag on hover with CSS.

Let’s understand it with examples.

Change background Image on hover

To change the image of a div, we can use the :hover selector to change the url source of the background-image property on mouse hover.

Let’s say we have an HTML div element with a class name as “my-image“.

<div class="my-image"></div>

Now let’s add the background image to the my-image div and add the :hover selector to change or swap the background when a user hovers over the div.

.my-image{
    background-image: url('image1.jpg');
    height: 100px;
    width: 100px;
}

.my-image:hover{
    background-image: url('image2.jpg');
}

Now, when a user hovers their mouse over the div, the background image (here image1.jpg) will be replaced by image2.jpg

Change image on hover using the display property

We can also change the image <img> tag on our HTML page using the display property of CSS.

We can hide an element using display:none and show/display an element using display:block with CSS.

Let’s see an example, here we have a parent div with the class name “img-wrapper“. And it contains two <img> tags.

<div class="img-wrapper">
    <img src="image1.jpg" />
    <img src="image2.jpg" class="hover-img" />
</div>

Here, we have two <img> tags, one with “hover-img” class.

Now let’s write the CSS to change/swap image1 with image2 on hover.

.img-wrapper {
    position: relative;
    height: 400px;
    width: 600px;
  }

.img-wrapper img {
    position: absolute;
    width: 100%;
    height: 100%;
}

.img-wrapper .hover-img {
    display: none;
}

.img-wrapper:hover .hover-img {
    display: block;
}

In the above example, we have set the position of the parent element (img-wrapper) as relative and set the child <img> elements as absolute.

Initially, we set the hover-img class to display:none, so that it won’t display when the page loads.

And when we hover our mouse over the parent element, the hover-img display property changes to display:block, which replace the “image1.jpg” in the parent element with “image2.jpg”.


Related Topics:

How to change image on hover using JavaScript

Change image src using onClick event in JavaScript

How to add background image with gradient overlay in CSS

Scroll to Top