How To Change An Image On Hover

by David Ugale

A common request in our website development projects is to have an image change when the mouse hovers over it.

For example, we might want to have this image:

look like this when the mouse hovers over it:

Our preferred method to do this is to use CSS to:

  1. Set an image as the background
  2. Use the background-position property to change the portion of the image that is shown


Create a new image that includes the default state of the image in the upper half and the hover state of the image in the lower half. Using the example above, we create an image that looks like this:

Note that the image is now twice the height. Most important, the top half of the image and the bottom half of the image are lined up and the same size.


Create an HTML element that uses the new image as a background. This example uses a button, but you can use any other element that you like, such as a div tag.


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


#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: 17px; /* only the top half of the image */
  width: 100px;

The resulting button will now look like this:


Add a hover state using background-position.


#hover-over-bg:hover {
  background-position: 0 -17px; /* this displays the bottom half of the image */

Now, when you hover over the image, you’ll see it change:

Neat! That’s all there is to it to create a nice hover effect for an image.