How To Change Image On Hover

David Ugale, Author
Written by David Ugale

A popular request in our website development projects is to transform an image when the user’s mouse hovers over it.

For example, the desired behavior is for this particular image:

Original Image

to display differently when the user’s mouse hovers over it:

Transformed Image

To accomplish this, our preferred method is to utilize CSS properties:

  1. Set the background property to an image that combines the original image with the desired hover over appearance.
  2. Use the CSS background-image property and the background-position property to display a different portion of the background image.

STEP 1:

Create another image that combines the original image with an image of the desired hover over appearance. The original image is placed in the top portion of the new image. The hover over appearance is placed in the bottom portion of the new image.

New Background Image

Note that the image is now double the original height. Most important, the top portion of the image and the bottom portion of the image are lined up and the exact same size.

STEP 2:

Create an HTML element that utilizes the newly created image as a background. This example incorporates a button. However, other elements, like a div, can work equally as well.

HTML
<button id="hover-over-bg" type="button"></button>

CSS
#hover-over-bg {
  background: none;
  background-image: url(/wp-content/uploads/2018/06/logo-text-only-100-bg.png);
  border: none;
  cursor: pointer; /* this makes the pointer look nicer */
  height: 38px; /* only the top half of the image */
  width: 184px;
}

The resulting button looks like this:

Final Image

STEP 3:

Add background-position to the CSS properties that belong to the hover pseudo class

CSS
#hover-over-bg:hover {
  background-position: 0 -38px; /* display the bottom portion of the image */
}

Now, hovering your mouse over the image causes a change in appearance:

Originally published June 19th, 2018, updated May 4th, 2022