EthicsComputerCourses
Join training +91 90532 10052

Animation Fill Mode

CSS · Lesson 105 of 240 Intermediate 10 min read Updated

By the end of this lesson you will be able to control what an element looks like before an animation starts and after it ends, write the animation shorthand without parsing surprises, run several animations on one element, and know what animation-composition is for. You will build a replayable demo of all four fill modes on a festival offer grid.

This lesson finishes the animation properties group. It builds on Keyframes, Animation Duration & Delay and Animation Iteration & Direction.

Before, during and after

Every animation has three phases:

  • Before: the delay, while the animation is waiting to start.
  • Active: the cycles are running.
  • After: all cycles have finished.

By default, keyframe styles apply only in the active phase. Before and after, the element shows its normal styles. Think of an actor in a school play. The costume is worn only while the curtain is up. Before the play and after it, the actor is in school uniform.

animation-fill-mode lets the costume stay on for longer.

ValueBefore (during the delay)After (when finished)
nonenormal stylesnormal styles
forwardsnormal styleskeeps the last keyframe that played
backwardsuses the first keyframe that will playnormal styles
bothuses the first keyframekeeps the last keyframe

Notice the words "that played". The keyframes used depend on direction and count:

  • With animation-direction: reverse, the first keyframe played is 100%, so backwards shows the 100% styles during the delay.
  • With animation-iteration-count: 2 and alternate, the last cycle runs backwards, so forwards keeps the 0% styles.
  • With a count of 0.5, forwards holds the element at the 50% point.

Step 1: see all four fill modes

Priya's gift shop in Pune shows four offer cards. Each card waits 1 second, then rises in over 1 second. The keyframes also turn the card gold at 100%, so you can see whether the end state is kept.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Fill modes side by side</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 24px; }
    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
      gap: 12px;
      max-width: 600px;
      margin-bottom: 16px;
    }
    .card {
      --rise: 30px;
      padding: 16px;
      border: 1px solid #cbd5e1;
      border-radius: 10px;
      background: #fff;
    }
    .card code { font-weight: 700; }
    .run .card { animation: offer-in 1s ease-out 1s; }
    .run .forwards { animation-fill-mode: forwards; }
    .run .backwards { animation-fill-mode: backwards; }
    .run .both { animation-fill-mode: both; }
    @media (prefers-reduced-motion: reduce) {
      .card { --rise: 0px; }
    }
    @keyframes offer-in {
      from { opacity: 0; translate: 0 var(--rise); }
      to { background: #fde68a; }
    }
  </style>
</head>
<body>
  <div class="grid run" id="offers">
    <div class="card"><code>none</code><p>Diyas, set of 12, ₹240</p></div>
    <div class="card forwards"><code>forwards</code><p>Rangoli kit, ₹180</p></div>
    <div class="card backwards"><code>backwards</code><p>Dry fruit box, ₹650</p></div>
    <div class="card both"><code>both</code><p>Torans, ₹320</p></div>
  </div>
  <button type="button" id="replay">Replay</button>
  <script>
    const offers = document.querySelector('#offers');
    document.querySelector('#replay').addEventListener('click', () => {
      offers.classList.remove('run');
      void offers.offsetWidth; // force the browser to notice the removal
      offers.classList.add('run');
    });
  </script>
</body>
</html>

Watch each card through one run:

  • none is visible during the delay, vanishes when the animation starts, rises, turns gold, then snaps back to white.
  • forwards also flashes during the delay, but stays gold at the end.
  • backwards stays hidden during the delay and rises smoothly, but loses the gold at the end.
  • both is hidden during the delay and stays gold. It is the only card with no jump at all.

The Replay button removes the run class, makes the browser recalculate styles by reading offsetWidth, and adds the class again, which restarts the animations. Under reduced motion, --rise is 0px, so the cards only fade and change colour.

forwards and the cascade

forwards feels like the easy way to keep an end state, but it has a cost. Styles from a running or filling animation beat every normal declaration in the cascade. If a card is held gold by forwards, a later :hover rule or a class added by JavaScript cannot change its background. Normal declarations cannot override it; !important ones can.

A more robust pattern is:

  1. Put the final look in the element's normal styles.
  2. Let the keyframes describe only the starting difference, as in from { opacity: 0; }.
  3. Use backwards (or both) so the start state covers the delay.

Then the end state is real CSS, it still works if the animation never runs, and hover styles behave normally. The staggered grid in Animation Duration & Delay used exactly this pattern.

The animation shorthand, and how it is read

The shorthand sets up to eight values for each animation:

CSS
.badge {
  /* name, duration, easing, delay, count, direction, fill, play state */
  animation: stamp-in 600ms ease-out 200ms 1 normal both running;
}

The order is mostly free, but the browser follows strict rules:

  • The first time is the duration and the second time is the delay. Their order always matters.
  • A keyword that fits another sub-property is given to that property the first time it appears. Only a word left over becomes the name.
  • Any value you leave out is reset to its initial value. That includes animation-timeline, which you cannot set in the shorthand at all.

The safe habit is to write the name first, then the duration, then the delay. This page shows how the browser reads five shorthand lines:

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>How the shorthand is read</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 24px; }
    pre { padding: 12px; border-radius: 8px; background: #f1f5f9; }
    .t1 { animation: pop 400ms 200ms both; }
    .t2 { animation: 200ms pop 400ms; }
    .t3 { animation: forwards 1s both; }
    .t4 { animation: reverse 2s reverse; }
    .t5 { animation: infinite 1s; }
  </style>
</head>
<body>
  <div class="t1"></div><div class="t2"></div><div class="t3"></div>
  <div class="t4"></div><div class="t5"></div>
  <pre id="report"></pre>
  <script>
    const lines = [];
    for (const box of document.querySelectorAll('[class^="t"]')) {
      const s = getComputedStyle(box);
      lines.push(`.${box.className}: name=${s.animationName} duration=${s.animationDuration} ` +
        `delay=${s.animationDelay} fill=${s.animationFillMode} direction=${s.animationDirection}`);
    }
    document.querySelector('#report').textContent = lines.join('\n');
  </script>
</body>
</html>
Output
.t1: name=pop duration=0.4s delay=0.2s fill=both direction=normal
.t2: name=pop duration=0.2s delay=0.4s fill=none direction=normal
.t3: name=both duration=1s delay=0s fill=forwards direction=normal
.t4: name=reverse duration=2s delay=0s fill=none direction=reverse
.t5: name=none duration=1s delay=0s fill=none direction=normal

This output is from Chrome. Line 2 swapped the times, so the duration is only 0.2s. In line 3, the first forwards became the fill mode and both was left over as a name. In line 5, infinite became the count and the animation has no name at all. That is why Keyframes told you not to name a rule after a keyword.

Several animations on one element

Separate animations with commas. Each position in a list belongs to the animation at the same position in animation-name:

CSS
.offer-banner {
  animation:
    slide-in 600ms ease-out both,
    glow 1.5s ease-in-out 600ms 3 alternate;
}

@keyframes slide-in { from { translate: -100% 0; opacity: 0; } }
@keyframes glow { to { box-shadow: 0 0 24px #facc15; } }

The banner slides in, and when it lands, it glows three times. Some rules to remember:

  • The number of animations is set by animation-name. If you list more durations than names, the extras are ignored. If you list fewer, the list repeats from the start.
  • If two animations change the same property at the same moment, the one later in the list wins.
  • To combine movements, give each animation its own property. One animation can use translate while another uses rotate or scale. With the single transform property, the two would overwrite each other. CSS Transform covers the individual properties, and 2D Transformations goes further.

animation-composition: a pointer

By default, an animation replaces the element's own value for a property. animation-composition changes that:

ValueResult
replaceThe keyframe value replaces the element's value (initial value)
addThe keyframe value is added on top of the element's value
accumulateThe values are combined into one value
CSS
.price-tag {
  translate: 50px 0;
  animation: nudge 1s linear;
  animation-composition: add;
}

@keyframes nudge {
  from { translate: 0 0; }
  to { translate: 100px 0; }
}

With replace, the tag would start at 0px and ignore its own 50px. With add, it moves from 50px to 150px. animation-composition has been Baseline since 2023, so it works in all current browsers. It matters most in animation systems where several layers of motion are mixed, which you will meet in Advanced Animation Systems.

Common mistakes

  • Delayed entrances without backwards or both. The element flashes in its final state before the animation starts.
  • Using forwards to hold important state. Later hover and class changes cannot override it. Put the end state in normal styles instead.
  • Putting the delay before the duration in the shorthand. The first time is always the duration.
  • Naming keyframes after keywords such as both, reverse or infinite.
  • Animating transform in two animations at once. The later one wins. Split the work across translate, rotate and scale.

Interview questions

1. What does animation-fill-mode: both do?

It combines backwards and forwards. During the delay, the element shows the first keyframe that will play. After the animation ends, it keeps the last keyframe that played. It is the usual choice for delayed entrance animations.

2. With forwards, which keyframe does the element keep?

The last one that actually played, which depends on direction and iteration count. With alternate and an even count, it is the 0% keyframe. With a fractional count, it is a point in between.

3. Why can a :hover style fail on an element with animation-fill-mode: forwards?

Values from an animation, including filled values, override all normal author declarations in the cascade. So the hover rule loses to the held keyframe. You can fix it by putting the final state in normal styles and filling only backwards, or by removing the animation.

4. How does the browser decide which time in the animation shorthand is the duration?

The first value that parses as a time is the duration, and the second is the delay. Other values can be in almost any order. Keywords go to their matching sub-properties first, and only a leftover word becomes the animation name.

5. Two animations on one element both animate transform. What happens, and how do you fix it?

The animation that comes later in the animation-name list wins for that property. Use the individual properties translate, rotate and scale so each animation controls a different property, or set animation-composition: add on the later one.

Key points

  • Keyframe styles apply only while an animation runs, unless animation-fill-mode says otherwise.
  • backwards covers the delay, forwards keeps the end, and both does both.
  • Filled values depend on direction and count, and they override normal styles in the cascade.
  • In the shorthand, the first time is the duration and the second is the delay; keywords are matched before the name.
  • The shorthand resets anything you leave out, including animation-timeline.
  • Comma lists run several animations; give each its own property, or use animation-composition (Baseline 2023).

Exercise

Aarav is launching a Holi sale page. Build a banner that runs two animations: it slides down from above the page in 500ms after a 300ms delay, and then its "Up to 50% off" text pulses three times. Make sure the banner is hidden during the delay and is never shown in its final position before the slide starts, but keep the final look in the normal styles rather than relying on forwards. Write the shorthand with the name first, then duration, then delay, and give each animation a different property. Under reduced motion, show the banner with no movement.

Show solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Holi sale banner</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 0; }
    .banner {
      padding: 20px;
      text-align: center;
      background: linear-gradient(90deg, #db2777, #7c3aed, #0ea5e9);
      color: #fff;
    }
    .banner strong { display: inline-block; font-size: 1.5rem; }
    @media (prefers-reduced-motion: no-preference) {
      .banner { animation: drop-in 500ms ease-out 300ms backwards; }
      .banner strong { animation: throb 600ms ease-in-out 800ms 6 alternate; }
    }
    @keyframes drop-in { from { translate: 0 -100%; opacity: 0; } }
    @keyframes throb { to { scale: 1.1; } }
  </style>
</head>
<body>
  <div class="banner"><strong>Up to 50% off</strong> on colours and pichkaris</div>
</body>
</html>

The banner only describes its start in drop-in and fills backwards, so it is hidden during the 300ms delay and ends on its normal styles. The text uses scale, a different property from the banner's translate, and starts at 800ms, when the slide has finished. Six alternate cycles make three full pulses that end at normal size.

Quick Quiz

1. An element has a 1s delay and animation-fill-mode: none. What does it show during the delay?

2. Which fill mode keeps the end state of the animation but not the start state during the delay?

3. In animation: 300ms slide 1s; what is the duration?

4. animation: forwards 1s both; gives which animation name?

5. Two animations in one list both set opacity at the same time. Which wins?

Learn CSS with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call