Snook.ca

Simplest CSS Slideshow

In continuing my exercise of tackling a simple slideshow in different ways, this challenge attempts to make a slideshow without using any JavaScript.

Thankfully, I didn’t research this first and just went with it. Yes, this has been done before by other people. Whatevs. Enjoy…

To do so, I’ll attempt to do this with CSS animations. This was trickier than expected because, well, math is hard. I knew I was dealing with certain multiples but kept screwing up the timing.

The basic premise is to have an image fade in and then fade out. I use an animation-delay to offset the animations for each subsequent image in the slideshow.

This graph visualizes how the animation duration and animation delay work.

There are 3 sets of numbers that you need to determine:

The total animation-duration.

The animation-delay for each image.

The keyframe timings.

Animation Duration

To determine the animation duration, take the fade in time that you want plus the time you want the image to be visible before beginning to fade out. If you want the image to take 1 second to fade in and be visible for 1 second and you have 3 images then your animation duration is 6 seconds.

Math: (fade-in + visible) × images = duration.

Animation Delay

The animation delay is pretty straightforward. The key thing is that you want to start the animation for the next image when the image before that is starting its fade-out. Therefore, you want the animation delay to be the fade-in time plus the visible time for the previous image. If it’s the second image and the animation should fade in for 1 second and be visible for 2 seconds before fading out then the animation delay should be 3 seconds. If it’s the third image, the delay is 6 seconds. If it’s the fourth image, the delay is 9 seconds, and so on.

Math: (fade-in + visible) × (ordinal position − 1) = delay.

Keyframes

Keyframes can be a simple from or to but for more complicated animations, we have to use percentages. Therefore, the last piece of the puzzle is figuring out how to get the animation percentages correct. To do so, we need to break up 100% into the number of seconds of our animation. If the animation is 10 seconds long then each second is 10%. If the animation is 6 seconds then each second is 16.66%. The timing then becomes a multiple of that.

Math: 100 ÷ animation duration = percentage for 1 second.

All Together

Here’s how it all comes together. In this case, I’m doing a 1 second fade-in plus 2 seconds of visibility before fading out. First, I define the CSS keyframes for a fade animation.

Sorry, comments are closed for this post. If you have any further questions or
comments, feel free to send them to me directly.

Hi. My name is Jonathan Snook and this is my site. I write about what interests me, which is usually web design, development, and technology. I'm also in the middle of a food adventure.
I wrote SMACSS. I tweet. Want to learn more?