Use :hover CSS Pseudo-Class with Opacity Property to Create "Fade-in"/"fade-Out" Effect

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a month ago

Learn how to change the "opacity" property of an element to create a "hover-over" effect with CSS using the :hover selector. The "opacity" property specifies the transparency level for an element (in this case, an image and paragraph text).

By changing the opacity, you can change how "faded" an image looks. By utilizing the :hover selector, you can set the opacity of an element to change on mouse-over to create a "fade in" or "fade out" effect.

Hiro Nishimura: [0:00] Create a new class in your CSS. I named mine effect. Set opacity to 100%. Opacity is the transparency level of the element, and goes from to 1, or % to 10%.

[0:11] Set the :hover selector to the class to change the opacity on mouseover. The :hover selector tells the browser what to do on mouseover. In this case, because I set the opacity to 30%, the element will have 30% opacity and will create the fade-out effect.

[0:28] The first element in this lesson is an image. Set the image class to effect. If you refresh the browser, you can see that the image has the fade-out effect at mouseover.

[0:40] To create the fade-in effect, you can flip the values. Keep in mind that these can be any pair of values between % and 100%. I'll stick with 30% and 100%. Now, when you refresh the page, you'll see you have the fade-in effect at mouseover.

[0:59] The element can also be text. Let's type in some text and set the class to effect. When we refresh the browser, we can see that both the image and the text have the fade-in effect at mouseover.

[1:13] We use the :hover selector to change the opacity of two elements, an image and text. By going from an opacity of less to more, in this case from 10% to 80%, we created the fade-in effect. By going from opacity of more to less, in this case from 80% to 10%, we created the fade-out effect.