Tania Rascia

Skip Navigation
Crossfade Between Two Images with CSS Animations

Crossfade Between Two Images with CSS Animations

 /  7 responses

A website I worked on wanted an animated, flashing neon sign. A gif is the first thing that comes to mind in such a situation, but unfortunately gifs do not allow partial transparency, and I needed to place this image on a textured background. The solution was to use CSS animations to alternate between two pngs.

I used a modified method from this guide by Rick Bradshaw.

View demo

Put the two images in an outer block element.

<section>
	<img class="bottom" src="img.png">
	<img class="top" src="img-2.png">
</section>

The outer will be relative and the inner will be absolute.

section {
  position: relative;
}

section img {
	position: absolute;
}

Create the animation and apply it to the top element.

.top {
	animation-name: fade;
	animation-timing-function: ease-in-out;
	animation-iteration-count: infinite;
	animation-duration: 1s;
	animation-direction: alternate;
}

@keyframes fade {
	0% {
		opacity: 1;
	}
	25% {
		opacity: 1;
	}
	75% {
		opacity: 0;
	}
	100% {
		opacity: 0;
	}
}

Note

Hi, my name is Tania Rascia. I've turned down every offer for advertisements or sponsored posts on this website. I write free resources that have helped thousands of people successfully transition into a web development career.

My committment is to no bullshit, no sponsored posts, no ads, and no paywalls. If you enjoy my content, please consider supporting what I do.

Support my work

Newsletter

New articles on web development every two weeks.

Write a response

Your email address will not be published.

All code will be displayed literally.

Discussion