⚠️ This lesson is retired and might contain outdated information.

Use the CSS background-image Property to Change Image on mouse-over

Share this video with your friends

Social Share Links

Send Tweet

In this lesson, you will set a background-image for a CSS class, and swap it out to another background-image on :hover to achieve the "change image on hover" effect.

The CSS background-image property allows you to set an image as a background of a DIV.

By creating a class with width, height, and the background-image set, you can insert a DIV in your HTML page set to that class, and utilizing the :hover pseudo-class, replace the image that shows up on mouse-over.

Hiro Nishimura: [0:00] Let's create a CSS class for this lesson. I'll name mine effect. I have two 300px by 200px images that I want to use to create the switch on hover effect. I will set the width and height of this class to 300px and 200px. Then, we set the background image property for this class by specifying the image url.

[0:20] In our index.html, we insert not an image but a div set to the class "effect." When we refresh the browser, we see that the image shows up. To better see how this image is a background to the div, let's enter some text.

[0:32] I'll create a paragraph element within the div. When we refresh the browser, we can see that the text seems to appear in front of the image. This is because the image is a background image. Now, let's set the hover pseudo-element so we can create effects to occur on mouseover.

[0:46] Because I have two images with the same width and height, I don't need to specify them again, since those properties will be inherited from the effect class. I'll just change the image. When we refresh the browser, we can see that the image changes on mouseover.

[0:59] We learned how to create a class with a background image so that we can create a change image on mouseover effect. We also inserted some text to show how this image is a background image and behaves how a background image on an HTML page would behave.

[1:12] By setting the width and height, we controlled how big the div is. By default, if I were to say double the width, because this is a background image, the image will repeat to fill the space.