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:
to display differently when the user's mouse hovers over it:
To accomplish this, our preferred method is to utilize CSS properties:
- Set the
background
property to an image that combines the original image with the desired hover over appearance. - Use the CSS
background-image
property and thebackground-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.
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.
<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: 38px; /* only the top half of the image */
width: 184px;
}
The resulting button looks like this:
STEP 3:
Add background-position
to the CSS properties that belong to the hover pseudo class
#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: