Chapter 28 of 33

Animations & Keyframes

In Transitions we animated an element from one state to another when something changed. That covers hover effects, but not a loading spinner that spins forever, a "New!" badge that pulses as soon as the page loads, or a heading that types itself out letter by letter.

For those we need CSS animations. You describe the motion as a series of keyframes (snapshots at chosen moments), and the browser fills in the frames between them. Animations can start by themselves, repeat, reverse, pause, and even be driven by the scroll position instead of the clock.


What is a CSS Animation?

A CSS animation changes property values over time following a sequence of keyframes defined with the @keyframes at-rule. It is attached to an element with the animation properties and does not need a state change to start.

Every animation has two parts:

  1. The @keyframes rule: what happens (the steps of the motion), with a name.

  2. The animation properties on an element: which element uses it, for how long, how many times, and so on.

The word "keyframe" comes from hand-drawn animation: a senior artist drew the key poses, and assistants drew the in-between frames. Here, you are the senior artist and the browser is the assistant.


Your First Animation

<span class="badge">New!</span>
@keyframes pulse {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(1.2);
  }
}

.badge {
  display: inline-block;     /* inline elements can't be transformed */
  background: crimson;
  color: white;
  padding: 4px 10px;
  border-radius: 999px;
  animation: pulse 0.8s ease-in-out infinite alternate;
}

Output: as soon as the page loads, the badge smoothly grows to 120% size and shrinks back, over and over, without anyone touching it.

Let's take this apart.


The @keyframes Rule

@keyframes name {
  0%   { /* styles at the start */ }
  50%  { /* styles halfway */ }
  100% { /* styles at the end */ }
}
  • The name is your choice (like a variable name). Use something descriptive: fade-in, spin, slide-up.

  • Each selector is a percentage of the animation's duration. from = 0% and to = 100%.

  • You can list several percentages together: 0%, 100% { opacity: 1; }.

  • The order you write them in doesn't matter; the percentages decide the timing.

A multi-step example

@keyframes traffic-light {
  0%   { background-color: red; }
  45%  { background-color: red; }
  50%  { background-color: green; }
  90%  { background-color: green; }
  95%  { background-color: orange; }
  100% { background-color: red; }
}

.light {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  animation: traffic-light 10s infinite;
}

With a 10-second duration, each percentage is a point in time: red until 4.5 s, a quick change to green by 5 s, green until 9 s, then orange and back to red. Giving two keyframes the same value (0% and 45% are both red) is how you make something hold still for a while.

Missing keyframes

  • If you leave out 0%/from or 100%/to, the browser uses the element's current style for the missing end. For example, @keyframes spin { to { transform: rotate(360deg); } } starts from whatever transform the element already has.

  • A property doesn't need to appear in every keyframe. Each property is interpolated between the keyframes in which it appears.

  • !important inside a keyframe is ignored, and so is that whole declaration.


The Animation Properties

PropertyWhat it controlsDefault
animation-nameWhich @keyframes to usenone
animation-durationLength of one cycle0s
animation-timing-functionEasing between keyframesease
animation-delayWait before the first cycle0s
animation-iteration-countNumber of cycles (can be a decimal or infinite)1
animation-directionnormal, reverse, alternate, alternate-reversenormal
animation-fill-modeStyles applied before start / after end: none, forwards, backwards, bothnone
animation-play-staterunning or pausedrunning

The shorthand

/* name | duration | timing | delay | count | direction | fill-mode */
animation: slide 2s ease-in-out 0.5s infinite alternate both;

As with transitions, the first time value is the duration and the second is the delay. The name can go anywhere, but avoid naming your keyframes after keywords like ease or infinite, which would confuse the parser. We checked how Chrome splits the line above: name slide, duration 2s, timing ease-in-out, delay 0.5s, count infinite, direction alternate, fill mode both.

Multiple animations on one element are comma-separated:

.typing {
  animation: typing 2s steps(21) both,
             blink 0.7s step-end infinite;
}

animation-direction

For a @keyframes grow that changes width from 100px to 200px over 1 second:

DirectionCycle 1Cycle 2Cycle 3
normal100 → 200100 → 200100 → 200
reverse200 → 100200 → 100200 → 100
alternate100 → 200200 → 100100 → 200
alternate-reverse200 → 100100 → 200200 → 100

alternate is what makes the badge pulse smoothly: without it, the badge would grow and then jump back to its small size at the start of every cycle.

With reverse and alternate, the timing function is reversed as well, so an ease-in going forwards becomes ease-out-like going backwards. That keeps the motion looking natural in both directions.


animation-fill-mode: Before and After

By default, an animation only affects the element while it is running. During the delay and after the end, the element shows its normal styles. This causes two classic surprises:

  • A fade-in with a delay shows the element fully visible during the delay, then suddenly makes it invisible and fades it in. (Flash!)

  • A slide-in animation finishes and the element jumps back to where it started.

animation-fill-mode fixes both:

ValueDuring the delayAfter the end
noneNormal stylesNormal styles
backwardsFirst keyframe's stylesNormal styles
forwardsNormal stylesLast keyframe's styles (stays put)
bothFirst keyframe's stylesLast keyframe's styles

"First" and "last" keyframes depend on the direction: with reverse, the first keyframe applied is 100%. And for forwards with an even number of alternate cycles, the element ends on the 0% keyframe.

Worked example

@keyframes grow {
  from { width: 100px; }
  to   { width: 200px; }
}

.bar {
  width: 50px;
  animation: grow 1s linear 1s;   /* duration 1s, delay 1s */
}

What is the width at 0.5 s and at 2.5 s with each fill mode?

Fill modet = 0.5 s (in the delay)t = 1.5 s (running, halfway)t = 2.5 s (finished)
none50px150px50px
backwards100px150px50px
forwards50px150px200px
both100px150px200px

We verified the none, backwards and forwards values in Chrome by pausing the animations at those times. Tip: both is a sensible default for one-shot entrance animations.


Timing Functions Work Per Keyframe

Here's a detail many people miss: animation-timing-function is applied to each segment between two keyframes, not to the animation as a whole.

@keyframes three-steps {
  0%   { width: 0px; }
  50%  { width: 100px; }
  100% { width: 200px; }
}

.bar {
  animation: three-steps 2s ease;
}

With ease, the bar speeds up and slows down twice: once from 0 to 100px, and again from 100 to 200px. In Chrome, the width at 0.5 s (halfway through the first segment) is 80.23px, exactly 80.2% of that segment, which is what ease gives at 50% progress (see the table in Transitions). At 1 s it's exactly 100px, and at 1.5 s it's 180.23px.

If you want one smooth motion across the whole thing, use linear as the animation's timing function. You can also set a different timing function for a single segment, inside a keyframe:

@keyframes drop {
  0%   { transform: translateY(-200px); animation-timing-function: ease-in; }
  70%  { transform: translateY(0);      animation-timing-function: ease-out; }
  85%  { transform: translateY(-30px);  animation-timing-function: ease-in; }
  100% { transform: translateY(0); }
}

This makes a ball fall (accelerating, ease-in), bounce up (decelerating, ease-out), and fall again, like real gravity.


Practical Examples

1. Loading spinner

<div class="spinner" role="status" aria-label="Loading"></div>
.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e5e7eb;
  border-top-color: #2563eb;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

Output: a light grey ring with one blue quarter, spinning clockwise once per second forever. linear is important here: with ease, it would slow down and speed up every turn, which looks like it is stuttering.

2. Fade-and-slide entrance

@keyframes slide-up {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.card {
  animation: slide-up 500ms ease-out both;
}

.card:nth-child(2) { animation-delay: 100ms; }
.card:nth-child(3) { animation-delay: 200ms; }

Output: the cards fade in and rise into place one after another (a "staggered" entrance). Thanks to both, cards 2 and 3 stay invisible during their delay instead of flashing.

3. Typewriter effect with steps()

<p class="typing">Learn CSS animations.</p>
.typing {
  font-family: monospace;      /* every character has the same width */
  width: 21ch;                 /* the text has 21 characters */
  white-space: nowrap;
  overflow: hidden;
  border-right: 3px solid;     /* the cursor */
  animation: typing 2s steps(21) both,
             blink 0.7s step-end infinite;
}

@keyframes typing {
  from { width: 0; }
}

@keyframes blink {
  50% { border-color: transparent; }
}

Output: the text appears one character at a time over 2 seconds while a cursor blinks at the end. Why it works:

  • In a monospace font, 1ch is the width of one character, so 21ch fits the 21-character text exactly.

  • steps(21) makes the width jump in 21 equal steps, one character per step, instead of sliding smoothly (which would reveal half-characters). In our test, at 1 second (halfway) the visible text was exactly "Learn CSS " (10 of 21 characters, since ⌊21 × 0.5⌋ = 10).

  • The typing keyframes have only a from; the end comes from the element's own width: 21ch.

  • step-end on the blink makes the cursor switch on and off sharply instead of fading.


Pausing and Controlling Animations

.marquee:hover {
  animation-play-state: paused;
}

Hovering pauses the animation at its current frame; leaving resumes it from there. This is important for accessibility: moving content that can't be paused is hard for many people to read.

JavaScript can react to animations through events:

const card = document.querySelector(".card");

card.addEventListener("animationstart", (e) => console.log("start:", e.animationName));
card.addEventListener("animationend", (e) => console.log("end:", e.animationName));

Output (for the slide-up card):

start: slide-up
end: slide-up

There's also animationiteration, fired at the end of each cycle except the last. An infinite animation never fires animationend.

To restart an animation from JavaScript, the usual trick is to remove the class, force the browser to notice (for example by reading element.offsetWidth), and add the class back.


Transitions vs Animations

TransitionAnimation
Starts whenA property value changesThe animation is applied (e.g. on page load)
Number of statesTwo (start and end)Any number of keyframes
Repeat / loopNoYes (animation-iteration-count)
Reverse / alternateOnly by changing the state backYes (animation-direction)
PauseNoYes (animation-play-state)
Best forHover/focus effects, toggling statesLoaders, attention effects, entrances, complex sequences

Animations in the cascade

While it runs, an animation overrides all normal declarations, whatever their specificity. Even an inline style="..." loses to a running animation. Only !important declarations (and transitions) beat animations. This follows from the cascade origins described in Specificity, Inheritance & the Cascade.


Scroll-Driven Animations

Normally an animation runs on a time timeline: 0% at the start, 100% after the duration. Scroll-driven animations replace the clock with the scroll position. Scroll down and the animation moves forward; scroll up and it goes backward. No JavaScript needed.

Reading progress bar

<div class="progress"></div>
.progress {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 6px;
  background: #2563eb;
  transform-origin: left;
  animation: fill-bar linear both;
  animation-timeline: scroll();     /* progress = how far the page is scrolled */
}

@keyframes fill-bar {
  from { transform: scaleX(0); }
  to   { transform: scaleX(1); }
}

Output: a thin blue bar at the top of the page that is empty at the top and grows as you scroll, reaching full width at the bottom. In Chrome, scrolling to exactly halfway (1428px of 2856px) gave transform: matrix(0.5, 0, 0, 1, 0, 0), i.e. scaleX(0.5), a half-full bar.

Things to notice:

  • No duration is given. With a scroll timeline, the "length" of the animation is the scroll distance.

  • animation-timeline must come after the animation shorthand. The shorthand resets animation-timeline to auto (the normal time-based timeline). In our test, writing them in the wrong order left the timeline at auto.

  • We animate transform: scaleX() instead of width for performance, as explained in Transitions.

Reveal on scroll with view()

view() tracks an element's journey through the visible area (the scrollport) instead of the whole page's scroll:

@keyframes reveal {
  from { opacity: 0; transform: translateY(40px); }
  to   { opacity: 1; transform: translateY(0); }
}

.reveal {
  animation: reveal linear both;
  animation-timeline: view();
  animation-range: entry 0% entry 100%;   /* run while the element is entering */
}

Each .reveal element fades and rises into place as it scrolls into view, which used to require JavaScript with IntersectionObserver.

Browser support

Scroll-driven animations have worked in Chrome and Edge since version 115 (2023) and in Safari since version 26 (2025). Firefox added support in version 159 (October 2026), so they have only just arrived in all major engines. Users on older browsers will simply not see the effect, so use them for enhancements (progress bars, reveal effects), never for something the page needs in order to work. You can test for support with @supports (animation-timeline: scroll()) { ... }.


Accessibility and Performance

  • Respect reduced motion. Wrap big or looping motion so users who have asked for less motion don't get it:

@media (prefers-reduced-motion: reduce) {
  .badge,
  .card,
  .reveal {
    animation: none;
  }
}
  • Avoid flashing. Content that flashes more than three times per second can trigger seizures in people with photosensitive epilepsy (this is a WCAG rule).

  • Animate transform and opacity whenever possible; avoid animating width, height, top or left.

  • Don't loop forever without reason. Infinite animations keep the CPU/GPU busy and distract readers. A spinner while loading is fine; a permanently bouncing button is not.


Common Mistakes

  • No duration. animation: pulse; has a duration of 0, so nothing visible happens.

  • Name mismatch. @keyframes fadeIn with animation-name: fade-in: names are case-sensitive and must match exactly.

  • Element jumps back at the end. Add animation-fill-mode: forwards (or both).

  • Element flashes before a delayed entrance. Use backwards or both.

  • Jerky loops. If the last keyframe doesn't match the first, the loop jumps; use alternate or make 0% and 100% the same.

  • Spinner wobbles. Use linear for continuous rotation.

  • Animating a plain inline element's transform. It's ignored; use inline-block.

  • Writing animation-timeline before the animation shorthand, which resets it.


Interview / Exam Questions

1. What is @keyframes and how is it connected to an element?

@keyframes name { ... } defines the stages of an animation as percentages of its duration (from = 0%, to = 100%). It is connected to an element by animation-name: name (or the animation shorthand) together with at least a non-zero animation-duration.

2. Explain animation-fill-mode forwards, backwards and both.

forwards keeps the last keyframe's styles after the animation ends. backwards applies the first keyframe's styles during the delay. both does both. With none (default), the element shows its normal styles before and after the animation.

3. An animation has duration 2s, delay 1s and iteration count 3. When does it end?

At 1 + 2 × 3 = 7 seconds after it is applied. The delay only happens once, before the first cycle.

4. What is the difference between alternate and reverse?

reverse plays every cycle backwards (100% → 0%). alternate plays forwards on odd cycles and backwards on even cycles, so the motion goes back and forth without a jump.

5. A @keyframes has stops at 0%, 50% and 100%, and animation-timing-function: ease. Is the ease applied once or twice?

Twice. The timing function applies to each segment between keyframes separately, so the element eases in and out between 0% and 50%, and again between 50% and 100%.

6. When should you use a transition and when an animation?

Use a transition for a simple change between two states triggered by something (hover, focus, a class toggle). Use an animation when you need more than two steps, automatic start, looping, alternating or pausing.

7. What does animation-timeline: scroll() do?

It links the animation's progress to the scroll position of the nearest scrolling ancestor (by default) instead of to time. At the top the animation is at 0%, at the bottom it's at 100%. It must be declared after the animation shorthand, which resets it.


Summary

  • An animation = a @keyframes rule (the steps) + animation properties on an element (how to play it).

  • Keyframes are percentages of the duration; missing from/to use the element's current style.

  • Key properties: name, duration, timing function, delay, iteration count, direction, fill mode, play state; in the shorthand the first time is the duration, the second the delay.

  • alternate gives smooth back-and-forth motion; forwards/backwards/both control styles outside the active period.

  • Timing functions apply per keyframe segment; steps() gives frame-by-frame effects.

  • Running animations override normal declarations, but not !important.

  • animation-timeline: scroll() / view() drive animations by scrolling, now in all major engines but very new in Firefox.

  • Prefer transform/opacity and respect prefers-reduced-motion.

Next, in Shadows & Filters, we'll add depth and visual effects to elements, many of which you can then bring to life with the transitions and animations you've just learned.