How to add a "background-image" to an "img" tag and switch display on mouseover?

Viewed 73

I have an img tag like this (and I can't use a container)

<img src="https://example.com/first-image.jpg" class="my-image">

And I would like to display a second image instead of the first one on mouseover using only CSS. Maybe doing something like this:

.my-image:hover {
    background-image: url("https://example.com/second-image.jpg");
}

I'm not sure if it that's possible. Any ideas?

1 Answers

Solution 1: HTML can be edited

You can do it by not using the src attribute and set the default image in your CSS, then change it on hover like so:

.my-image {
  width: 200px;
  height: 200px;
  background-image: url(https://....jpg);
  background-size: cover;
  background-position: center;
}
.my-image:hover {
  background-image: url(https://....jpg);
}

See working example here: https://jsfiddle.net/86ujL1dv/

Note that modern browsers don't load images until they're needed, so there will be a slight delay on the first hover, as the user's browser will load the second picture.

Solution 2: HTML cannot be edited

It's a bit of a hack, but you can set the size of the img to zero, and use padding to make it look the same, then use the background-image property, like so:

.my-image {
  width: 200px;
  height: 200px;
}
.my-image:hover {
  width: 0;
  height: 0;
  padding: 100px;
  background-size: cover;
  background-position: center;
  background-image: url(https://images.pexels.com/photos/4017166/pexels-photo-4017166.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260);
}

See live example here: https://jsfiddle.net/1bo7L89w/

Related