Fading 2 Images Using CSS

Here is a nifty bit of code for fading two images – no Flash, no animated GIFs, just pure CSS3 and HTML.

We’re going to be fading these 2 images:

green black

With the end result looking like this:

This is the CSS that drives the fading:

#fade {  
width:300px; //width of images
height:300px; //height of images

#fade img {
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;

@keyframes FadeInOut {
0% {opacity:1;}
45% {opacity:1;}
55% {opacity:0;}
100% {opacity:0;}

#fade img.top {
animation-name: FadeInOut;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
animation-duration: 8s;
animation-direction: alternate;


The top image is placed directly over the bottom image and then fades in and out to reveal the image underneath. Pretty simple.

The above CSS code should be pasted into your stylesheet or embedded into your page header in between <style></style> tags.

Then, paste this HTML code where you would like your images to be, replacing “URL” with the URLs of your two images:

<div id="fade">
  <img class="bottom" src="URL" />
  <img class="top" src="URL" />

There you go, a quick and simple way to fade images. Make sure both your images have the same dimensions for smooth fading.