CSS Keyframe Animation with Delay Between Iterations

Avatar of Chris Coyier
Chris Coyier on

Say you want an animation to run for 1 second, but then delay for 4 seconds before running again. Seems like that would be easy. Turns out it’s not-so-straightforward, but doable. You need to fake it.

Nope

There is an animation-delay property, but that won’t help us here. That delays the start of the animation, but after it’s started it runs continuously.

Solution: Keyframes with No Changes

You’ll need to do a little mental math:

I want the animation to run for 1 second.

~ plus ~

I want the animation to delay for 4 seconds in between iterations.

~ equals ~

5 total seconds

So when you call the keyframe animation, you use the total seconds:

.mover {
  animation: move 5s infinite;
}

But now our @keyframes will run for 5 seconds:

@keyframes move {
  /* this will happen over 5 seconds */
}

So to make our animation run for only 1 second, you’ll need to have the changes happen over 1/5 of the time, or 20%. Verbously, that would look like this:

@keyframes move {
  0% {
    transform: translate(0, 0);
  }

  /* Finish changes by here */
  20% {
    transform: translate(200px, 0);
  }

  /* Between 20% and 100%, nothing changes */
  100% {
    transform: translate(200px, 0);
  }
}

We can write with less code, since the 0% values are assumed and you can comma separate keyframe steps:

@keyframes move {
  20%, 100% {
    transform: translate(200px, 0);
  }
}

You can get as fancy as you want with the keyframes, you just need to remember to have everything set exactly the same between the final step of your animation and 100%.

Demo

See the Pen Keyframe with Animation Delay Between Iterations by Chris Coyier (@chriscoyier) on CodePen.