Demo 1 - One image to another, on hover

Plan

  1. Put one image on top of the other
  2. Change the opacity of the top image on hover

Demo

Demo 2 - One image to another, when a button is pressed (transitions)

Plan

Same as before, but instead of using the :hover pseudo class, we are going to use javascript to add a toggle a class. I'm using jQuery here because it's easy to understand, though you could just use plain old JS.

Demo

Click me to toggle

Demo 3 - One image to another with a timer (CSS animations)

Plan

You could implement this by using Javascript to toggle classes with a delay - that would allow older browsers to still have the images change. As we are looking forward though, we'll use CSS keyframes.

  1. Start with two images absolutely positioned on top of each other.
  2. Use CSS keyframes to define two states, one with top image transparent, one with it opaque.
  3. Set the animations number of iterations to infinite.

Demo

Each image is visible for 9 seconds before fading to the other one.

To make sense of that, I've defined 4 keyframes, specified that whatever has this animation attached will be opaque for the first 45%, then transparent for the last 45%. The animation will repeat forever, will last 10 seconds, and will run forward then backwards. In other words, image 1 will be visible for 4.5 seconds, followed by a 1 second fade, followed by 4.5 seconds of image 2 being visible. Then it will reverse, meaning that image 1 and 2 will both be visible for 9 (4.5 x 2) seconds each time.

Demo with multiple images

Demo 4 - More than just fades

This technique isn't limited to just fades, you can animate almost every property. Here are a couple of examples.

Zooming in and out

Hover on the image

Rotation

Hover on the image

Demo 5 - Animating the background-image property

Right now this only works on webkits built from 2012 onwards. It's not part of the spec (yet?).

Plan

  1. Make a div with a width and height
  2. Change the background-image property

Demo

Demo 6 -Fading between multiple images on click

Image 1 Image 2 Image 3 Image 4