CSS animation-direction: alternate for Smooth Loops

This article explains the CSS animation-direction: alternate property, detailing how it works, why it eliminates jarring visual snaps in keyframe cycles, and how developers can use it to build seamless, continuous looping animations. By understanding this property, you can write cleaner, more efficient CSS without duplicating keyframe steps.

The animation-direction property in CSS defines whether an animation should play forward, backward, or alternate back and forth between the two. By default, animations run with animation-direction: normal, meaning every cycle starts at 0% (from) and progresses to 100% (to). When set to loop with animation-iteration-count: infinite, a default animation immediately snaps back to the starting state the instant it finishes, creating a visible and often undesirable jump.

Setting the value to alternate completely removes this snap by reversing the playback direction on every other cycle:

  • Odd-numbered iterations (1st, 3rd, 5th, etc.): The animation plays forwards from 0% to 100%.
  • Even-numbered iterations (2nd, 4th, 6th, etc.): The animation plays in reverse from 100% back to 0%.

Why It Creates Smooth Loops

Without alternate, achieving a smooth back-and-forth animation requires manually coding the return trip inside the @keyframes rule. For instance, to make an element move right and come back, you would have to define:

@keyframes slideManual {
  0% { transform: translateX(0); }
  50% { transform: translateX(100px); }
  100% { transform: translateX(0); }
}

While functional, this approach complicates timing functions and inflates keyframe declarations. With animation-direction: alternate, you only define the one-way transition:

@keyframes slide {
  from { transform: translateX(0); }
  to { transform: translateX(100px); }
}

.box {
  animation-name: slide;
  animation-duration: 2s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

In this implementation, the element smoothly glides to 100px over two seconds, then smoothly reverses back to 0px over the next two seconds.

Timing Functions in Reverse Cycles

A key advantage of animation-direction: alternate is how it handles timing functions like ease-in or ease-out. When an iteration plays in reverse, the timing function is inverted automatically. An ease-in acceleration at the start of a forward cycle becomes an ease-out deceleration at the end of the reverse cycle, preserving the physical realism and continuity of the motion throughout the entire loop.

Requirements

To see the smooth looping effect of alternate:

  1. animation-iteration-count must be set to a value greater than 1, most commonly infinite. If set to 1, the animation will only play once forward and stop, rendering the alternate behavior inactive.
  2. The keyframes should define distinct starting and ending values to provide a noticeable trajectory for the reversal.