Make Web Page Elements Fade In and Out With CSS3

Create fading effects on images, buttons, and more

The new styles introduced in CSS3 gave web professionals the ability to add Photoshop-like effects to their pages. One visual effect you can add using CSS3 is to make web pages interactive by creating faded areas that come into focus when a site visitor does something, like hovering over that element. This effect uses a combination of opacity and transition.

Change Opacity on Hover

One interactive element is to change the opacity of an image when a customer hovers over that element. For this example (the HTML is shown below), we use an image with the class attribute of greydout.

To make it greyed out, add the following style rules to your CSS stylesheet:

.greydout {
-webkit-opacity: 0.25;
-moz-opacity: 0.25;
opacity: 0.25;

These opacity settings translate to 25 percent. This means that the image will be shown as 1/4 of its normal transparency. Fully opaque with no transparency would be 100 percent, while 0 percent would be completely transparent.

Next, to make the image come clear (or more accurately, to become fully opaque) when the mouse hovers over it, you would add the following:

.greydout:hover {
-webkit-opacity: 1;
-moz-opacity: 1;
opacity: 1;

More Opacity Adjustments

You will notice that, for these examples, we use the vendor-prefixed versions of the rule to ensure backward compatibility for older versions of those browsers. While this is a good practice, the opacity rule is well supported by browsers, and it is safe to drop those vendor-prefixed lines.

Still, there's no reason not to include these prefixes if you want to ensure support for older browser versions. Just be sure to follow the accepted best practice of ending the declaration with the normal, un-prefixed version of the style.

When deployed on a site, this opacity adjustment is an abrupt change. First, it's grey, and then it's not, with no interim states between those two. It is like a light switch—on or off. This may be what you want, but you may also want to experiment with a change that is more gradual.

To add a nice effect and make this fade gradual, add the transition property:

class:.greydout {
-webkit-opacity: 0.25;
-moz-opacity: 0.25;
opacity: 0.25;
-webkit-transition: all 3s ease;
-moz-transition: all 3s ease;
-ms-transition: all 3s ease;
-o-transition: all 3s ease;
transition: all 3s ease;

mla apa chicago
Your Citation
Kyrnin, Jennifer. "Make Web Page Elements Fade In and Out With CSS3." ThoughtCo, Jul. 31, 2021, Kyrnin, Jennifer. (2021, July 31). Make Web Page Elements Fade In and Out With CSS3. Retrieved from Kyrnin, Jennifer. "Make Web Page Elements Fade In and Out With CSS3." ThoughtCo. (accessed March 31, 2023).