Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 139 ยท Transforms and Animation

Keyframe Animations

Build CSS keyframe animations. Define @keyframes, then control duration, delay, iteration, direction, fill-mode and play-state, and stagger and pause motion.

Transitions animate between two values when something changes. That covers a lot, but not everything. A loading spinner has to turn forever. A notification badge might pulse three times and stop. A hero illustration might move through five poses. None of these has a "before" and "after" triggered by a state change.

For that, CSS has keyframe animations. You describe the motion once, in an @keyframes rule, as a series of snapshots. Then you attach it to any element with the animation properties, which control how long it runs, how many times, in which direction, and what happens before and after.

Defining keyframes

An @keyframes rule has a name and a list of keyframes. Each keyframe is a percentage of the animation's duration, with the styles the element should have at that moment:

CSS
@keyframes bounce {
  0%   { translate: 0 0; }
  40%  { translate: 0 -30px; }
  60%  { translate: 0 -30px; }
  100% { translate: 0 0; }
}

The browser fills in all the frames between the keyframes, just like a transition. Some handy shortcuts:

  • from means 0% and to means 100%.
  • Several selectors can share one block: 40%, 60% { translate: 0 -30px; }.
  • If you leave out 0% or 100%, the browser uses the element's normal styles for that end. So @keyframes fade { from { opacity: 0; } } fades in to whatever opacity the element already has.

Keyframe names are custom identifiers. Pick descriptive names like spin or slide-in, and avoid CSS keywords such as none or initial.

Attaching an animation

To run keyframes on an element, you need at least two properties: the name and a duration.

CSS
.logo {
  animation-name: bounce;
  animation-duration: 1s;
}

Like transitions, the default duration is 0s, so an animation without a duration finishes instantly. The full list of longhand properties is:

Property What it controls Default
animation-name Which @keyframes to run none
animation-duration Length of one cycle 0s
animation-timing-function Easing between keyframes ease
animation-delay Wait before starting (can be negative) 0s
animation-iteration-count How many cycles; a number or infinite 1
animation-direction normal, reverse, alternate, alternate-reverse normal
animation-fill-mode Styles applied before and after running none
animation-play-state running or paused running

The animation shorthand accepts them all in almost any order. As with transitions, the first time is the duration and the second is the delay:

CSS
.logo {
  animation: bounce 1s ease-in-out 0.5s infinite alternate;
}
Three looping animations

Look at the bounce keyframes: they set animation-timing-function inside a keyframe. Easing applies to each segment between two keyframes, not to the whole animation. Here the ball slows on the way up (ease-out) and speeds up on the way down (ease-in), like real gravity.

Iteration and direction

animation-iteration-count can be any positive number, including fractions: 2.5 plays two and a half cycles. Use infinite for loops.

animation-direction decides which way each cycle plays:

  • normal: 0% โ†’ 100% every time.
  • reverse: 100% โ†’ 0% every time.
  • alternate: forward, then backward, then forward. Great for smooth back-and-forth motion without writing the return trip.
  • alternate-reverse: backward first, then forward.

With alternate, each forward and each backward pass counts as one iteration. Easing is reversed on backward passes too, so ease-in becomes ease-out on the way back.

fill-mode: before and after

By default, an animation only affects an element while it runs. During a delay, the element shows its normal styles; when the animation ends, it jumps back to them. Often that's wrong. A heading that fades in after a 1-second delay is visible for that second, then disappears and fades in. A box that slides to the right snaps back to the left when it finishes.

animation-fill-mode fixes both problems:

  • none (the default): keyframe styles apply only while running.
  • forwards: after finishing, the element keeps the styles of the last keyframe.
  • backwards: during the delay, the element already has the styles of the first keyframe.
  • both: forwards and backwards together. This is the safe choice for most entrance animations.
Comparing fill modes

The script uses a small trick to replay an animation: remove the class, read a layout property such as offsetWidth so the browser notices the removal, then add the class again. Simply re-adding a class that's already there does nothing.

forwards has a side effect. A filled animation keeps overriding the property, so later changes from hover rules or JavaScript seem to be ignored. That's because animations sit above normal declarations in the cascade. If you need the final state to be editable, set the final values in the normal rule as well and use backwards fill instead.

Delays and staggering

animation-delay waits before the first cycle. It doesn't repeat between iterations; for a pause between loops, build it into the keyframes (for example, make the motion happen between 0% and 60% and keep it still until 100%).

A negative delay starts the animation partway through, immediately. That's useful for staggering loops: three dots with delays of 0s, -0.2s and -0.4s are all moving from the very first frame, just out of sync. Custom properties keep this tidy:

CSS
.dot { animation: wave 1.2s ease-in-out infinite; animation-delay: calc(var(--i) * -0.15s); }
HTML
<span class="dot" style="--i: 0"></span>
<span class="dot" style="--i: 1"></span>
<span class="dot" style="--i: 2"></span>

Pausing with play-state

animation-play-state: paused freezes an animation exactly where it is, and running continues from that point. You can toggle it from CSS, for example on hover, or from JavaScript. Giving users a way to pause looping motion is an accessibility requirement for anything that moves for more than five seconds alongside other content.

A marquee you can pause

The seamless loop works because the list contains two identical copies of the items and the animation moves it by exactly -50%, one copy's width. At the end of each cycle, the second copy sits exactly where the first one started, so the jump back is invisible.

Animation events

JavaScript can react to animations with three events: animationstart, animationiteration (at the end of each cycle except the last) and animationend. Each event has an animationName property, so one listener can handle several animations. A common use is removing an "entrance" class once the animation is done.

For more control, the Web Animations API lets JavaScript run the same keyframes directly with element.animate(), and element.getAnimations() returns the CSS animations running on an element so you can pause, reverse or seek them.

Multiple animations

Separate animations with commas, in the shorthand or in each longhand:

CSS
.badge {
  animation:
    pop 300ms ease-out both,
    glow 2s ease-in-out 300ms infinite alternate;
}

If two animations change the same property, the one listed last wins. That's another reason the individual translate, rotate and scale properties are so handy: one animation can move an element while another rotates it, without fighting over transform.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does from mean in an @keyframes rule?

    from is an alias for 0% and to is an alias for 100%.
  2. 2. An animation slides a box and then snaps back to its start. Which declaration keeps the final position?

    forwards keeps the styles of the last keyframe after the animation finishes.
  3. 3. How does animation-direction: alternate behave?

    Alternate cycles switch direction, which gives smooth back-and-forth motion without writing the return trip as keyframes.
  4. 4. What does a negative animation-delay such as -0.5s do?

    Negative delays start the animation partway through its cycle, which is handy for staggering loops so they are all moving from the first frame.
  5. 5. Where does a timing function set inside a keyframe apply?

    Easing in a keyframe controls the movement between that keyframe and the following one, which lets you build gravity-like motion.

Summary

  • @keyframes name { ... } describes snapshots at percentages; from and to mean 0% and 100%.
  • Attach keyframes with animation-name and animation-duration, or the animation shorthand.
  • animation-iteration-count and animation-direction control loops; alternate creates back-and-forth motion.
  • animation-fill-mode: both applies the first keyframe during the delay and keeps the last one afterward.
  • Negative delays stagger loops; animation-play-state pauses and resumes.
  • Animation events and getAnimations() let JavaScript react to and control CSS animations.
  • Offer a pause control for long-running motion and tone it down for prefers-reduced-motion: reduce.

Next: Scroll-driven Animations โ€” link an animation's progress to scrolling instead of time.