graphicsmotion

motion basics

css transitions, the web animations api, what's cheap to animate, reduced motion, and springs.

report a mistake
.md

change a property and let the browser draw the frames in between. pick the api by how much control you need, the property by what it costs, and check the reduced motion setting before anything moves.

transition
css one control, the target
animate()
a handle pause, seek, reverse, finished
cheap
transform, opacity style and composite only
costly
layout left, width, height, margin
reduced motion
reduce swap the slide for a fade
critical damping
2√(km) fastest with no overshoot
reach for it
  • hover and focus states
  • showing and hiding
  • moving things between places
  • a drag that settles
on this page
  1. css transitions vs the web animations api
  2. transform + opacity
  3. will-change
  4. prefers-reduced-motion
  5. spring physics
  6. pitfalls
  7. sources

motion on the web is mostly one move: change a property, and the browser draws the frames between the old value and the new one. this sheet covers the two ways to ask for that, css transitions and the web animations api, which properties stay cheap to animate, the will-change hint, the reduced motion setting, and springs for motion with some weight to it.

css transitions vs the web animations api

a transition is a standing rule on an element: when this property changes, take this long to get there. change the value, from a stylesheet or from script, and the browser tweens from wherever it is now.

.card {
  transition: translate 300ms ease; /* property, duration, easing, then an optional delay */
}
.card:hover {
  translate: 0 -4px;
}

the shorthand sets transition-property, transition-duration, transition-timing-function and transition-delay, which start at all, 0s, ease and 0s. so transition: 300ms alone tweens every property that changes, and with no duration a change just jumps.1 ease is cubic-bezier(0.25, 0.1, 0.25, 1), and ease-in, ease-out and ease-in-out are (0.42, 0, 1, 1), (0, 0, 0.58, 1) and (0.42, 0, 0.58, 1).2

a transition needs two values it can interpolate. display has nothing in between, so it jumps, unless you add transition-behavior: allow-discrete, which level 2 lets you write in the shorthand. then display keeps its visible value for the whole run, so a fade out finishes before display: none lands.34 firefox doesn’t transition display yet; chromium and safari do.5

/* fade out, then display: none. fade back in when it's shown again */
.popup {
  transition:
    opacity 200ms,
    display 200ms allow-discrete;
}
.popup.closed {
  opacity: 0;
  display: none;
}
@starting-style {
  .popup {
    opacity: 0; /* where the fade in starts, on the first frame it's shown */
  }
}

the web animations api is the same model with a handle. element.animate() takes keyframes and timing, starts playing, and returns an Animation you can play(), pause(), reverse(), finish() and cancel(). it reports currentTime, playbackRate and playState (idle, running, paused or finished), and its finished promise resolves when it ends.6

const anim = card.animate([{ translate: "0 0" }, { translate: "0 -4px" }], {
  duration: 300,
  easing: "ease",
});
anim.pause();
anim.currentTime = 150; // seek, in ms
anim.playbackRate = 0.5; // half speed
anim.reverse(); // flips the rate and plays, back toward the start
await anim.finished; // resolves at the end. cancel() rejects it

its options have defaults of their own: duration 0, easing linear (css uses ease), fill none, delay 0, iterations 1, direction normal.7 with no fill, the element snaps back when the animation ends. fill: 'forwards' holds the last frame, but over the element’s own style, for as long as the animation exists. the spec would rather you write the end state into style and let the animation go:8

const lift = card.animate([{ translate: "0 -4px" }], {
  duration: 300,
  fill: "forwards",
});
await lift.finished;
lift.commitStyles(); // writes the end state into the style attribute
lift.cancel(); // and drops the animation
css transitiontransition: translate 1s linear
the one control it has

set a target. the browser tweens from wherever the dot is

element.animate()duration 1000, easing linear, fill both

nothing yet. play() makes the animation and starts it

two tracks with a dot each. the top dot moves with a css transition, translate 1s linear, and its one button sets the target, left or right. press it mid-way and the dot turns around from where it is. after each trip a readout gives the share of the way the dot had to go, the length the spec gives that trip, the length of the browser's own CSSTransition, and transitionend's elapsedTime. the bottom dot moves with element.animate(): play and pause, reverse, finish, a currentTime slider, and a readout of playState, playbackRate, currentTime and whether the finished promise resolved. under reduced motion the transition is off and the dot jumps, and the animation never plays: finish jumps it to the end, a step button walks it 100 ms at a time, and the slider scrubs.

the same move, two ways. the transition has one control, the target. the animation has the handle.

send the top dot back before it arrives and it turns around from where it is, and the way back is shorter: a 1 s linear transition cut at 0.3 s turns around in 0.3 s. the spec shortens a reversed transition to the share of the way it had covered, and plays the whole easing curve again rather than starting in its middle.9 the browser reports each one with transitionrun, transitionstart, transitionend and transitioncancel events, which carry an elapsedTime in seconds.10

which one: a transition for state you can write as css, like hover, focus, open and closed, or a class that comes and goes. animate() when you need to pause, scrub, reverse, wait on finished, or build keyframes from numbers you only have at runtime. a running transition is an Animation too: card.getAnimations() hands it back as a CSSTransition, handle included. that’s where the figure reads each trip’s length.11

transform + opacity

every visual change goes down the same pipeline: style, layout, paint, composite. change left or width and the box’s geometry changes, so the browser lays the page out again, repaints, and composites. a color change skips layout but repaints. transform and opacity can skip both: when the element has a compositor layer of its own, the compositor moves or fades that layer, and nothing is laid out or painted again. chromium runs those animations on its compositor thread, off the main thread.1213

at 60 hz the whole frame has 16.7 ms, at 120 hz 8.3 ms. web.dev’s rule of thumb leaves your own code about 10 ms of the 16.7, since the browser needs the rest.14

animate
  1. style
  2. layout
  3. paint
  4. composite

transform reruns 2 of 4: on a layer of its own, the layer just lands somewhere else: no layout, no paint.

lit stages rerun for the change. struck ones are skipped

a select picks a property, left, width, background-color, transform or opacity, and a run button moves the box in a track, or changes its color or its opacity, with a 600 ms transition on that property. four boxes under it name the stages of a frame, style, layout, paint and composite, and light the ones that rerun: all four for left and width, three for background-color with layout skipped, and two for transform and opacity, style and composite. a line says why. under reduced motion the change jumps.

pick a property and run it. the lit stages are the work the browser redoes on every frame of that change.

so move with translate, resize with scale, show and hide with opacity, and keep top, left, width, height and margin for layout you mean. a transform doesn’t move anything around the element: the box keeps its slot in the flow, and only its pixels go elsewhere.15 translate, rotate and scale are properties of their own since transforms level 2, so one can change without restating a whole transform list. they work in every engine since august 2022.16

/* instead of left: 0 -> 200px */
.item {
  transition: translate 200ms ease-out;
}
.item.moved {
  translate: 200px 0;
}

/* instead of animating height. the content squashes with it */
.sheet {
  transform-origin: top;
  transition: scale 200ms ease-out;
}
.sheet.closed {
  scale: 1 0;
}

/* show and hide. opacity 0 still takes clicks, hence pointer-events */
.toast {
  transition: opacity 150ms linear;
}
.toast.gone {
  opacity: 0;
  pointer-events: none;
}

to animate a real layout change, flip it: measure the element, apply the new layout, measure again, then play the difference back as a transform from the old place to the new one. paul lewis named it for its steps: first, last, invert, play.17

const first = el.getBoundingClientRect();
el.classList.add("moved"); // the real layout change
const last = el.getBoundingClientRect();
el.animate(
  [
    { translate: `${first.left - last.left}px ${first.top - last.top}px` },
    { translate: "0 0" },
  ],
  { duration: 300, easing: "ease-out" },
);

one side effect to know: any transform other than none, even one that changes nothing like translate: 0, makes the element a stacking context and the containing block for its position: fixed descendants. a fixed menu inside a transformed parent sticks to the parent, not the viewport. so leave translate unset at rest, as the code above does.1516

will-change

a hint, given ahead of time: this element is about to change in this way. a browser may answer will-change: transform by giving the element a layer of its own before the move starts, so the first frame doesn’t pay to set one up. the spec’s own reason: that setup can delay the start of a transform animation by a noticeable fraction of a second.18

/* a click comes at least 200 ms after the hover: time to set up */
.button {
  transition: opacity 200ms;
}
.button:hover {
  will-change: opacity;
}
.button:active {
  opacity: 0.3;
}

/* when the change happens on hover itself, hint on an ancestor's hover */
.list:hover > .item {
  will-change: translate;
}
.item {
  transition: translate 150ms;
}
.item:hover {
  translate: 4px 0;
}
// from script: on when a change is likely, off when it's done
opener.addEventListener("pointerenter", () => {
  drawer.style.willChange = "translate";
});
drawer.addEventListener("transitionend", () => {
  drawer.style.willChange = "auto";
});

the spec’s rules for it. don’t spread it over many elements or properties: the optimizations behind it can take a lot of memory, and overused they slow the page down or even crash it. keep it out of stylesheets unless the element really is always about to change, like a sidebar that slides out. give it time: set right before the change, it does little or nothing. take it off when the change is done, or the browser keeps the optimizations much longer than it would on its own.19 web.dev says to reach for it only once you see a graphics problem, and mdn calls it a last resort for a performance problem you already have, not a way to head one off.20

it changes things before anything moves, too. if any value of a property other than its initial one would make the element a stacking context or a containing block, naming that property in will-change does it now: will-change: transform makes both, will-change: opacity a stacking context.21

card a getswill-change:
card atooltip, z-index: 10
card b

no hint, no side effects. the tooltip still paints over card b: its z-index counts in the page.

card a and card b are positioned, with no z-index of their own

two overlapping cards, a and b, positioned with no z-index of their own, and a tooltip with z-index 10 hanging out of card a over card b. a select sets card a's will-change to auto, transform, opacity or left. with auto or left the tooltip paints over card b. with transform or opacity card a becomes a stacking context, and card b, later in the document, covers the tooltip. a line names the side effects each value brings.

the dropdown that vanished behind the next card: a stacking context you didn't ask for.

prefers-reduced-motion

the media feature has two values, no-preference and reduce. reduce means the person told their system they want an interface that removes or replaces motion that causes discomfort for people with vestibular sensitivity, or distraction for people with attention deficits.22 wcag’s criterion 2.3.3, at level aaa, asks that motion started by an interaction can be turned off unless it’s essential. its definition of motion is a change in perceived size, shape or position, so a fade, a color change or a blur isn’t motion. so reduce isn’t a request for no animation: swap the slide for a fade, and drop motion that only decorates, like parallax.23

@keyframes slide-up {
  from {
    translate: 0 24px;
    opacity: 0;
  }
}
@keyframes fade-in {
  from {
    opacity: 0;
  }
}

.toast {
  animation: slide-up 450ms cubic-bezier(0.2, 0.7, 0.2, 1);
}
@media (prefers-reduced-motion: reduce) {
  .toast {
    animation: fade-in 200ms linear;
  }
}

/* or the other way around: the fade by default, the slide for people who haven't asked for less */
.note {
  animation: fade-in 200ms linear;
}
@media (prefers-reduced-motion: no-preference) {
  .note {
    animation: slide-up 450ms cubic-bezier(0.2, 0.7, 0.2, 1);
  }
}
const query = matchMedia("(prefers-reduced-motion: reduce)");
let reduced = query.matches;
query.addEventListener("change", () => {
  reduced = query.matches; // it can change while the page is open
});

toast.animate(
  reduced
    ? [{ opacity: 0 }, { opacity: 1 }]
    : [
        { translate: "0 24px", opacity: 0 },
        { translate: "0 0", opacity: 1 },
      ],
  { duration: reduced ? 200 : 450, easing: "ease-out" },
);
your system
checking
this url
no override
play it as
saved

the full version slides up 24px while it fades in, 450 ms. that follows the setting above.

a fade changes nothing about where the card is or how big, so it stays

a readout of what your system says, prefers-reduced-motion reduce or no-preference, and whether the url has ?motion=reduced. two buttons choose full or reduced, preset from that, and play runs a small card's entrance with element.animate: the full version slides up 24px while it fades in over 450 ms, the reduced one fades in where it is over 200 ms. a line says which one played.

the same entrance both ways. the default follows your setting; the buttons let you compare.

the setting lives in the os. macos: system settings, accessibility, motion (display, up to macos 15), reduce motion. ios: settings, accessibility, motion. windows 11: settings, accessibility, visual effects, animation effects. android 9 and later: settings, accessibility, remove animations.24 to check a page without changing it, chrome’s devtools can fake it from the rendering tab, under emulate css media feature prefers-reduced-motion.25 this site also reads ?motion=reduced from the url, in the hook its figures use:

site/src/visuals/kit/use-reduced-motion.ts
import { useEffect, useState } from 'react';

/** true when the OS asks for reduced motion, or the url has ?motion=reduced (for testing) */
export function useReducedMotion(): boolean {
  const [reduced, setReduced] = useState(false);
  useEffect(() => {
    const forced = new URLSearchParams(window.location.search).get('motion') === 'reduced';
    const query = window.matchMedia('(prefers-reduced-motion: reduce)');
    const update = () => setReduced(forced || query.matches);
    update();
    query.addEventListener('change', update);
    return () => query.removeEventListener('change', update);
  }, []);
  return reduced;
}

spring physics

an easing runs on a clock: a duration and a curve. a spring runs on physics: a position, a velocity, and a force pulling toward the target. so it can be interrupted, retargeted mid-flight, or launched with the speed of the finger that let go, and it ends when it comes to rest. the model is a damped harmonic oscillator, with three numbers:

each step: a = (-k * (x - target) - c * v) / m, then update v and x. the damping ratio ζ = c / 2√(km) says what comes out: below 1 it overshoots and rings, at exactly 1, critical damping, it gets in fastest without crossing the target, and above 1 it creeps in.

with k = 100 and m = 1, critical damping is c = 20. the figure starts at c = 10, ζ = 0.5: it overshoots by 16% and stays within 1% of the target from 0.88 s on. at c = 20 that takes 0.66 s, and at c = 40, ζ = 2, 1.75 s. at c = 0 it never settles, and swings once every 0.63 s.

critical c = 2√(km) = 20.0 · ζ = 0.50
0s0.5s1s1.5s2starget

underdamped: it overshoots. overshoot 16%. settles in 0.88 s.

the same spring as css
transition: translate 0.9s linear(0, 0.038, 0.138, 0.275, 0.43, 0.588, 0.737, 0.867, 0.967, 1.05, 1.109, 1.145, 1.161, 1.161, 1.15, 1.13, 1.106, 1.08, 1.055, 1.032, 1.013, 0.997, 0.986, 0.979, 0.975, 0.973, 0.974, 0.977, 0.981, 0.985, 0.989, 1);

three sliders, stiffness 10 to 600, damping 0 to 80 and mass 0.5 to 5, starting at 100, 10 and 1. release lets a dot go from the left of a track toward a dashed target line. the track has the same scale as a chart under it of the dot's position over 2 seconds, and a time slider scrubs both. a readout gives the critical damping, 2 root k m, the damping ratio, the regime, underdamped, critical or overdamped, the overshoot and the settle time: 16% and 0.88 s for the starting spring. a button sets the damping to exactly critical. under it, the same spring as css, a transition with a linear() easing of 32 stops, and a copy button. under reduced motion release shows the end state, and the slider still scrubs.

k pulls, c brakes, m resists. the dashed line is the target. critical damping is the fastest curve that never crosses it.

in a frame loop, let the screen hand out time and the physics spend it in fixed steps, carrying what’s left to the next frame. then a slow frame or a fast screen doesn’t change the motion. glenn fiedler’s fix your timestep! lays out the pattern.2627

const k = 100;
const c = 10;
const m = 1;
const dt = 1 / 480; // one fixed step, in seconds
let x = 0;
let v = 0;
const target = 1;
let owed = 0; // time the physics hasn't spent yet
let last = performance.now();

const accel = (x, v) => (-k * (x - target) - c * v) / m;

function frame(now) {
  owed += Math.min((now - last) / 1000, 0.1); // a hidden tab doesn't catch up all at once
  last = now;
  while (owed >= dt) {
    // velocity verlet: move, then update the speed with the average of both accelerations
    const a1 = accel(x, v);
    const x2 = x + v * dt + 0.5 * a1 * dt * dt;
    const a2 = accel(x2, v + a1 * dt);
    v += 0.5 * (a1 + a2) * dt;
    x = x2;
    owed -= dt;
  }
  el.style.translate = `${x * 200}px 0`;
  if (Math.abs(x - target) > 0.001 || Math.abs(v) > 0.001)
    requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

css can’t take a force, but it can take the curve. linear() takes a list of output values and, unless you give them positions, spreads them evenly over the run, so a spring sampled 32 times becomes an easing, and transition: translate 0.9s linear(…) plays it. the spec’s own example builds a bounce from many points the same way.28 linear() works in every engine since december 2023.29 the catch: the curve has a fixed length and shape, so it can’t carry the speed of a drag or turn around mid-flight the way the loop can.

pitfalls

sources

  1. css transitions level 1 (opens in a new tab), sections 2.1 to 2.5 for the four longhands, their initial values and the shorthand, and section 3: a transition starts when the old and new values can be interpolated and the duration plus the delay is more than 0s. ↩

  2. css easing functions level 1 (opens in a new tab), section 2.2: the keyword values and the cubic-bezier() each one stands for. ↩

  3. css transitions level 2 (opens in a new tab), sections 2.1, 2.5 and 2.6: with normal, transitions start only for interpolable properties, allow-discrete adds discrete ones, which flip at 50% progress, and the shorthand takes it as a fifth value. ↩

  4. css display level 4 (opens in a new tab), section 2.9: display animates discretely, except that between none and another value, every point strictly between the ends takes the value that isn’t none. the element is inert while it’s on its way to none. ↩

  5. mdn’s transition-behavior (opens in a new tab) page and its compatibility table: transitioning display works in chrome 117 and safari 18, and not in firefox. ↩

  6. web animations level 1 (opens in a new tab), section 6.4, the Animation interface and its play states, and section 6.8: animate() builds a KeyframeEffect and an Animation and plays it. ↩

  7. web animations level 1 (opens in a new tab), section 6.5.1, the EffectTiming dictionary: delay 0, endDelay 0, fill auto (none for a keyframe effect), iterationStart 0, iterations 1, duration auto (treated as 0), direction normal, easing linear. ↩

  8. web animations level 1 (opens in a new tab), section 4.6 on fill behavior: authors are discouraged from fills that last forever and should prefer to set the final state in specified style, and the example that awaits finished, calls commitStyles() and then cancel(). ↩ ↩2

  9. css transitions level 1 (opens in a new tab), section 3: the new transition’s reversing shortening factor is the share of the way the old one had covered, in value, not time, and its duration is the specified duration times that factor. section 3.1 explains why: the second of two interrupted transitions is made shorter, and the whole timing function is used rather than jumping into its middle. ↩

  10. css transitions level 1 (opens in a new tab), section 6: the four events, and elapsedTime, in seconds, not counting the delay. ↩

  11. css transitions level 2 (opens in a new tab), section 6.1: CSSTransition extends Animation and adds transitionProperty. mdn’s CSSTransition (opens in a new tab) page: in every engine since july 2020. ↩

  12. rendering performance (opens in a new tab) on web.dev, by paul lewis: the pixel pipeline, javascript, style, layout, paint and composite, and the three paths a change can take through it. mozilla’s animation performance and frame rate (opens in a new tab): the same waterfall, with left, max-width, border-width, margin-left and font-size as layout properties, color as paint only, and transform and opacity, on a layer of their own, handled in composition. ↩

  13. stick to compositor-only properties and manage layer count (opens in a new tab) on web.dev: transforms and opacity are the two properties the compositor can handle alone, the element has to be on a layer of its own, and every layer costs memory and management. chrome’s renderingng architecture (opens in a new tab) page lists the full set of stages and says animations of visual effects can skip layout, pre-paint and paint and run entirely on the compositor thread. ↩

  14. rendering performance (opens in a new tab) on web.dev: at 60 refreshes a second the browser has 16.66 ms a frame, and with its own overhead, your work should fit in 10 ms. the 120 hz figure is the same division, 1000 / 120. ↩

  15. css transforms level 1 (opens in a new tab), section 3: the transform property does not affect the flow of the content around the element, and any value other than none creates a stacking context and a containing block for all descendants, fixed ones included. ↩ ↩2

  16. css transforms level 2 (opens in a new tab), section 5: the translate, rotate and scale properties, where every value but none, identity values like translate: 0px included, creates a stacking context and a containing block, as transforms do. mdn’s translate (opens in a new tab) page: in every engine since august 2022. ↩ ↩2

  17. paul lewis, flip your animations (opens in a new tab), february 2015: first, last, invert, play, with the same steps done through element.animate(). ↩

  18. css will change level 1 (opens in a new tab), section 1: an element moved with transforms might be promoted to a layer, setting that layer up is relatively expensive and can delay the start of the animation by a noticeable fraction of a second, and will-change lets the browser do it ahead of time. ↩

  19. css will change level 1 (opens in a new tab), section 1.2, using will-change well: don’t spam it across properties or elements, use it sparingly in stylesheets (a sidebar that slides out is the spec’s example of when it fits), give it time (a hover before a click usually gives at least 200 ms, since human reaction time is slow, and an ancestor’s hover can give lead time for a hover effect), and remove it when the element has stopped changing. section 2 adds that a browser may stop promoting elements when too many ask, to avoid exhausting gpu memory. ↩ ↩2

  20. web.dev’s animations guide (opens in a new tab), on forcing layer creation: use it only when you notice a graphics issue, give the browser time, and remove it when the change stops. mdn’s will-change (opens in a new tab) page: a last resort for existing performance problems, not a way to anticipate them, and in every engine since january 2020. ↩

  21. css will change level 1 (opens in a new tab), section 2: if any non-initial value of a property would create a stacking context, or a containing block for absolutely or fixed positioned elements, naming it in will-change must do the same. the example given is opacity, which creates a stacking context at any value other than 1. ↩

  22. media queries level 5 (opens in a new tab), section 12.1: the prefers-reduced-motion feature, its two values, and what reduce indicates. ↩

  23. wcag 2.2 (opens in a new tab), success criterion 2.3.3 animation from interactions, level aaa, and its glossary entry for motion animation, which leaves out changes of color, blur or opacity that don’t change perceived size, shape or position. the understanding document (opens in a new tab) describes the vestibular reactions it guards against and names parallax scrolling as motion that’s often not essential. ↩

  24. mdn’s prefers-reduced-motion (opens in a new tab) page: where the setting is on each system, and in every engine since january 2020. ↩

  25. chrome devtools’ emulate css media features (opens in a new tab) page: the rendering tab’s prefers-reduced-motion option. ↩

  26. glenn fiedler, fix your timestep! (opens in a new tab), june 2004: each rendered frame adds its real time to an accumulator, the simulation takes it out in steps of one fixed size, the leftover waits for the next frame, and a cap on the frame time keeps a slow simulation from falling further and further behind. ↩

  27. the html standard: requestAnimationFrame stores a callback (animation frames (opens in a new tab), section 8.12), and the event loop runs the stored callbacks once per rendering update, with the frame’s timestamp, just before it recalculates style and layout (processing model (opens in a new tab), section 8.1.7.3). ↩

  28. css easing functions level 2 (opens in a new tab), section 2.1: the linear() function, how stops without a position are spread evenly between their neighbors, and the bounce example built from many points. ↩

  29. mdn’s linear() (opens in a new tab) page: available across browsers since december 2023. ↩

  30. css transitions level 1 (opens in a new tab), section 3: a style change event processes a set of simultaneous changes, the spec doesn’t say when one happens, and implementations typically have one per screen refresh and when a script api needs up-to-date style or layout. transitions start from the values that changed in that event, against the values as of the previous one. level 2 (opens in a new tab), section 6.2, has the example that reads getComputedStyle between two writes. ↩

  31. css transitions level 2 (opens in a new tab), section 3.3: an element that wasn’t rendered at the previous style change event has no before-change style, and @starting-style supplies the starting style in its place. mdn’s @starting-style (opens in a new tab) page: in every engine since august 2024. ↩

  32. css grid layout level 1 (opens in a new tab), section 7.2: grid-template-rows animates item by item when the two track lists have the same length. mdn’s grid-template-rows (opens in a new tab) compatibility table: animating it works in chrome 107, firefox 66 and safari 16. ↩

  33. mdn’s interpolate-size (opens in a new tab) page and its compatibility table: allow-keywords lets sizes animate to and from keywords like auto, in chrome 129, and not in firefox or safari. ↩