Adding a hover effect to your CSS image

ยท

2 min read

Adding a hover effect to your CSS image

Images are created using the image tag <img /> in the HTML. However, you may wish to make the image display another property, or even a gif, when you hover over it. One way this can be done is by creating the image using CSS. That is, by styling an empty div and setting the background to be the chosen image. Afterward, you can then create the hover effect. In this article, I will walk you through how it can be achieved.

step 1

Create an empty div with a class name in HTML

<div class="bday-img"></div>

step 2

Select the image element using the class selector, add a background property, and set the image as the value. Then you may wish to add other properties to make the image fit properly into the div container.

.bday-img {
  background: url("path/to/image-file");
  background-size: cover;
  width: 400px;
  Height: 400px;
}

step 3 OR

Create the effect you wish the image to have when hovered over. You can achieve this by selecting the div as the case may be and adding :hover as part of the div property. Then include other values or features you wish the image to have when hovered over.

div:hover {
  background: red;
  color: black;
  font-size: 18px;
}

step3

Alternatively, you may wish that the image renders a gif when hovered over. That is, to create a GIF background as the hover effect. You can achieve that also by adding the gif as the background value in the :hover pseudo-class selector. Then style the gif to fit properly.

div:hover {
  background-image: url("path/to/gif-file");
  background-size: cover;
}

Conclusion

We examined how we can create a hover effect over an image by creating the image using CSS. That is by rendering it as a background image and then, using the :hover pseudo-class selector to create the hover effect. Also, we looked at how to add a gif as the background image when you hover over the image.

I hope this helps ๐Ÿค—

ย