0
0
CssHow-ToBeginner · 3 min read

How to Use animation-fill-mode in CSS: Syntax and Examples

The CSS property animation-fill-mode controls how an element's styles are applied before and after an animation runs. You can set it to none, forwards, backwards, or both to keep the animation's styles visible outside the animation duration.
📐

Syntax

The animation-fill-mode property accepts these values:

  • none: No styles are applied outside the animation time.
  • forwards: Keeps the styles from the animation's last keyframe after it finishes.
  • backwards: Applies the styles from the first keyframe during the animation delay.
  • both: Combines forwards and backwards, applying styles before and after the animation.
css
animation-fill-mode: none | forwards | backwards | both;
💻

Example

This example shows a box that changes color and stays that color after the animation ends using animation-fill-mode: forwards;.

css
html, body {
  height: 100%;
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f0f0;
}

.box {
  width: 150px;
  height: 150px;
  background-color: blue;
  animation-name: changeColor;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

@keyframes changeColor {
  from { background-color: blue; }
  to { background-color: orange; }
}
Output
A square box initially blue smoothly changes to orange over 3 seconds and stays orange after the animation ends.
⚠️

Common Pitfalls

Many forget to set animation-fill-mode, so the element snaps back to its original style after the animation ends. Also, using backwards without an animation delay has no visible effect because the first keyframe styles apply only during the delay.

Example of a common mistake:

css
.box {
  width: 100px;
  height: 100px;
  background-color: red;
  animation-name: moveRight;
  animation-duration: 2s;
  /* Missing animation-fill-mode */
}

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

/* Corrected with fill mode */
.box-fill {
  animation-fill-mode: forwards;
}
Output
Without fill mode, the box moves right then jumps back to start; with fill mode, it stays at the moved position.
📊

Quick Reference

ValueEffect
noneNo styles applied before or after animation
forwardsKeeps styles from last keyframe after animation ends
backwardsApplies first keyframe styles during animation delay
bothApplies styles before and after animation

Key Takeaways

Use animation-fill-mode to control if animation styles stay before or after the animation runs.
forwards keeps the end style visible after animation finishes.
backwards applies start styles during delay but needs a delay to show effect.
Without setting fill mode, elements revert to original styles after animation ends.
Combine animation-fill-mode with animation-delay for advanced timing control.