Skip to main content

Frontend development · Intermediate · 22 min

Animate with CSS and respect reduced motion

By Padding · Updated 18 Nov 2026
Modern browsers · CSS Transitions, CSS Animations Level 1 and Media Queries Level 5 · checked in Chromium with Playwright 1.65.1

You will add three purposeful animations to the Larkfield Clinic booking flow with CSS transitions and keyframes, give each one a calmer version for people who ask for less motion, and prove both versions with a browser test.

On this page

Motion in an interface should answer a question the person is already asking: did my tap register, what just changed, am I done? Motion that answers none of these is decoration, and decoration that moves is the kind most likely to make someone with a vestibular condition feel dizzy or sick. Operating systems let people ask for less motion, and browsers pass that request to CSS as the prefers-reduced-motion media feature. Your job is to listen to it, not by deleting every animation, but by giving each one a version that keeps its meaning without the movement.

This tutorial works on the Larkfield Clinic booking app, a fictional community clinic used across the design track. The patient is booking a Nurse appointment on Tuesday 9 December and wants 10:30. You will add three animations, each with a reason:

  • Selected slot. The tick in the chosen time grows into place, so the choice clearly registered.
  • Notice banner. When a time is taken by someone else, the "10:30 was just taken" banner slides down a short way, so a change the patient did not cause gets noticed.
  • Booked tick. On the Booked screen, the tick pops once to mark the end of the task.

Every animation moves only transform and opacity. The browser can run changes to those two properties without recalculating layout or repainting the page, which keeps them smooth on a low-end Android phone. The whole thing is plain CSS and about twenty lines of JavaScript, so there is no animation library for patients on prepaid data to download.

Step 1 · Build the page without any motion

Make a demo folder with four files: the page, a base stylesheet, an empty motion stylesheet and a small script. The page holds a shortened Pick a time screen and the Booked screen, which starts hidden. The colours come from the Larkfield high-fidelity design: accent #0F5E5A, accent-tint #E3F0EE, notice #8A5A00 on notice-tint #FFF4DC, border #7D8592 and canvas #F6F7F8.

Bash
mkdir -p ~/larkfield-motion-demo
cd ~/larkfield-motion-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pick a time · Larkfield Clinic</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="motion.css">
  <script src="app.js" defer></script>
</head>
<body>
  <main>
    <section id="pick">
      <h1>Pick a time</h1>
      <p class="service">Nurse appointment · 15 min</p>
      <div id="notice-region" role="status"></div>
      <fieldset>
        <legend>Tue 9 Dec</legend>
        <div class="slots">
          <label class="slot"><input type="radio" name="slot" value="09:00"><svg class="tick" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3L13 4.5" fill="none" stroke="currentColor" stroke-width="2"/></svg>09:00</label>
          <label class="slot"><input type="radio" name="slot" value="09:20"><svg class="tick" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3L13 4.5" fill="none" stroke="currentColor" stroke-width="2"/></svg>09:20</label>
          <label class="slot"><input type="radio" name="slot" value="10:30"><svg class="tick" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3L13 4.5" fill="none" stroke="currentColor" stroke-width="2"/></svg>10:30</label>
          <label class="slot"><input type="radio" name="slot" value="11:00"><svg class="tick" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8.5l3.2 3L13 4.5" fill="none" stroke="currentColor" stroke-width="2"/></svg>11:00</label>
        </div>
      </fieldset>
      <div class="actions">
        <button type="button" id="book">Book this time</button>
        <button type="button" id="simulate-taken" class="secondary">Demo: someone takes 10:30</button>
      </div>
    </section>

    <section id="booked" hidden>
      <div class="banner success">
        <svg class="booked-tick" viewBox="0 0 28 28" aria-hidden="true"><circle cx="14" cy="14" r="14" fill="currentColor"/><path d="M8 14.5l4 4 8-8.5" fill="none" stroke="#FFFFFF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
        <h1 tabindex="-1">You're booked</h1>
      </div>
      <p>Nurse appointment</p>
      <p class="time">Tuesday 9 December, 10:30</p>
      <p class="service">Larkfield Clinic</p>
    </section>
  </main>
</body>
</html>
HTML

The base stylesheet sets the look of every state, with no motion at all. The ticks sit in every slot but are transparent until their slot is chosen, so the time text never shifts sideways when a tick appears.

Bash
cd ~/larkfield-motion-demo
cat > style.css <<'CSS'
:root {
  --accent: #0F5E5A; --accent-tint: #E3F0EE; --on-accent: #FFFFFF;
  --text: #1B1F24; --text-muted: #5A6270; --surface: #FFFFFF; --canvas: #F6F7F8;
  --border: #7D8592; --notice: #8A5A00; --notice-tint: #FFF4DC;
}
* { box-sizing: border-box; }
body { margin: 0; background: var(--canvas); color: var(--text); font-family: system-ui, sans-serif; line-height: 1.5; }
main { max-width: 30rem; margin: 0 auto; padding: 1rem; }
.service { color: var(--text-muted); margin-top: 0; }
fieldset { border: 0; padding: 0; margin: 0 0 1rem; }
legend { font-weight: 600; margin-bottom: 0.5rem; }
.slots { display: flex; flex-wrap: wrap; gap: 0.5rem; }
.slot { position: relative; display: inline-flex; align-items: center; gap: 0.375rem; min-height: 44px; padding: 0 0.875rem; border: 1px solid var(--border); border-radius: 0.5rem; background: var(--surface); cursor: pointer; }
.slot input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; }
.slot:has(input:checked) { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
.slot:has(input:focus-visible) { outline: 3px solid var(--text); outline-offset: 2px; }
.slot:has(input:disabled) { color: var(--text-muted); border-style: dashed; cursor: not-allowed; }
.tick { width: 1rem; height: 1rem; opacity: 0; }
.slot:has(input:checked) .tick { opacity: 1; }
.banner { display: flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1rem; border-radius: 0.5rem; margin: 0 0 1rem; }
.banner.notice { background: var(--notice-tint); color: var(--notice); }
.banner.success { background: var(--accent-tint); color: var(--accent); }
.banner.success h1 { margin: 0; font-size: 1.375rem; }
.booked-tick { width: 1.75rem; height: 1.75rem; flex: none; }
.time { font-size: 1.75rem; font-weight: 700; margin: 0.25rem 0; }
.actions { display: flex; flex-wrap: wrap; gap: 0.5rem; }
button { min-height: 44px; padding: 0 1.25rem; border: 0; border-radius: 0.5rem; background: var(--accent); color: var(--on-accent); font: inherit; font-weight: 600; cursor: pointer; }
button.secondary { background: var(--surface); color: var(--text); border: 1px solid var(--border); }
CSS
touch motion.css

The script does two things. This is a shortened version of the picker in build a time slot picker with radio buttons and the status region in announce errors and notices with a live region; see those for why the radios and the status region are built this way. The demo button stands in for the server telling the app that 10:30 has gone: it disables that slot and adds the notice to a role="status" region, which already exists on the page so screen readers announce what is put into it. The Book button shows the Booked screen and moves focus to its heading.

Bash
cd ~/larkfield-motion-demo
cat > app.js <<'JS'
const region = document.querySelector('#notice-region');

document.querySelector('#simulate-taken').addEventListener('click', () => {
  if (region.firstChild) return;
  const taken = document.querySelector('input[value="10:30"]');
  taken.checked = false;
  taken.disabled = true;
  const banner = document.createElement('p');
  banner.className = 'banner notice';
  banner.textContent = '10:30 was just taken. These times are still free.';
  region.append(banner);
});

document.querySelector('#book').addEventListener('click', () => {
  const chosen = document.querySelector('input[name="slot"]:checked');
  if (!chosen) {
    document.querySelector('input[name="slot"]:not(:disabled)').focus();
    return;
  }
  document.querySelector('#booked .time').textContent = `Tuesday 9 December, ${chosen.value}`;
  document.querySelector('#pick').hidden = true;
  const booked = document.querySelector('#booked');
  booked.hidden = false;
  booked.querySelector('h1').focus();
});
JS

Check it worked

Open index.html in your browser (open index.html on macOS, xdg-open index.html on Linux, or drag the file into a window). Click 10:30: the chip turns dark green and a white tick appears at once. Click "Demo: someone takes 10:30": a yellow banner appears above the times and 10:30 gets a dashed border. Reload, choose 10:30 and click "Book this time": the Booked screen shows "You're booked" with a green tick and "Tuesday 9 December, 10:30". Everything works and nothing moves. That is the baseline every reduced-motion version must still match.

Step 2 · Write down what each animation is for

Before writing any keyframes, write the plan at the top of motion.css. Keeping every animation in one file, with its reason and its reduced version beside it, makes motion easy to review and easy to switch off when something goes wrong.

Bash
cd ~/larkfield-motion-demo
cat > motion.css <<'CSS'
/* Larkfield motion. Only transform and opacity move.
   1. Selected slot: the tick grows in, so the choice registers.
      Reduced: the tick appears at once.
   2. Notice banner: slides down 8px, so a change the patient did not cause is seen.
      Reduced: fades in, no movement.
   3. Booked tick: pops once, to mark the end of the task.
      Reduced: fades in, no scaling. */
CSS

Three rules shape the numbers you will use:

  • Short. Feedback on a tap should finish in about 100 to 200 milliseconds; anything that announces a new state can take up to about 400. Longer than that and people wait for the interface instead of using it.
  • Small distances. The banner moves 8 pixels, not in from off-screen. Large movement across the view is what most often triggers motion sickness.
  • Once. None of the three loops. WCAG success criterion 2.2.2 Pause, Stop, Hide (level A) asks for a way to pause moving content that starts by itself, lasts more than five seconds and runs alongside other content. Not looping avoids that control altogether.
  • Switchable. All three animations are triggered by something the patient does or by a change on the page. WCAG success criterion 2.3.3 Animation from Interactions (level AAA) asks that motion triggered by interaction can be turned off unless it is essential. The reduced-motion versions later in this tutorial are how you meet it.

Check it worked

motion.css starts with a comment that lists three animations, a reason for each and a reduced version for each. If you cannot write a reason for an animation, leave it out.

Step 3 · Animate the selected slot with a transition

A transition animates a property between two values when a selector starts or stops matching. Here the tick changes from opacity: 0 to 1 when its slot is checked, and you add a scale from 40 per cent to full size. A transition suits this because the tick moves between two states and back: choosing a different slot shrinks the old tick out with the same timing.

Bash
cd ~/larkfield-motion-demo
cat >> motion.css <<'CSS'

/* 1. Selected slot */
.slot .tick {
  transform: scale(0.4);
  transition:
    opacity 120ms ease-out,
    transform 180ms cubic-bezier(0.3, 1.4, 0.6, 1);
}
.slot:has(input:checked) .tick {
  transform: scale(1);
}
CSS

The curve cubic-bezier(0.3, 1.4, 0.6, 1) overshoots slightly past full size before settling, which makes the tick feel placed rather than faded. The chip's colour still changes at once: the tick carries the motion, and the instant colour change means the selection never waits on an animation.

Check it worked

Reload and click 10:30, then 11:00. The tick in 10:30 grows into place with a small bounce, and when you choose 11:00 it shrinks away as the new tick grows. The time text beside it does not move sideways. Use the arrow keys inside the group too: the same transition runs for keyboard selection, because it is driven by :checked, not by a click handler.

Step 4 · Slide the notice banner in with keyframes

A transition needs a before and an after on the same element. The notice banner has no before: it is added to the page. A keyframe animation runs when an element first appears, which is what you want here. Define the movement once with @keyframes, then attach it:

Bash
cd ~/larkfield-motion-demo
cat >> motion.css <<'CSS'

/* 2. Notice banner */
@keyframes banner-in {
  from { opacity: 0; transform: translateY(-0.5rem); }
  to   { opacity: 1; transform: translateY(0); }
}
.banner.notice {
  animation: banner-in 240ms ease-out;
}
CSS

ease-out starts fast and slows down, so the banner arrives quickly and settles. The transform moves the drawn banner without changing the layout: the slots below shift down once, when the banner is inserted, and the animation never shoves them around frame by frame. The same rule also runs the animation when an element goes from display: none to visible, which the next step relies on.

Check it worked

Reload and click "Demo: someone takes 10:30". The yellow banner fades in while dropping a short way into place, in about a quarter of a second. Click the button again: nothing happens, because the script only adds the banner once.

Step 5 · Pop the success tick on the Booked screen

The Booked tick uses keyframes too, with a middle stop that overshoots to 115 per cent before settling at full size. It starts 150 milliseconds after the screen appears, so the heading lands first and the tick confirms it.

Bash
cd ~/larkfield-motion-demo
cat >> motion.css <<'CSS'

/* 3. Booked tick */
@keyframes tick-pop {
  0%   { opacity: 0; transform: scale(0.4); }
  60%  { opacity: 1; transform: scale(1.15); }
  100% { opacity: 1; transform: scale(1); }
}
.booked-tick {
  animation: tick-pop 400ms 150ms cubic-bezier(0.2, 0.8, 0.3, 1) both;
}
CSS

The final keyword, both, is the fill mode. Without it the tick would show at full size during the 150 millisecond delay, then vanish and pop. both applies the first keyframe during the delay and keeps the last one when the animation ends.

Check it worked

Reload, choose 10:30 and click "Book this time". The Booked screen appears, and a moment later the green tick grows a little too big and settles beside "You're booked". It does not flash at full size first.

Step 6 · Give each animation a reduced-motion version

Now the part that matters most. Add a prefers-reduced-motion: reduce block that replaces each animation with the version you wrote down in the plan. Movement and scaling go; a short fade stays where it still helps the patient notice a change.

Bash
cd ~/larkfield-motion-demo
cat >> motion.css <<'CSS'

/* Reduced motion: same meaning, no movement */
@keyframes fade-in {
  from { opacity: 0; }
}
@media (prefers-reduced-motion: reduce) {
  .slot .tick { transform: none; transition: none; }
  .banner.notice { animation: fade-in 200ms ease-out; }
  .booked-tick { animation: fade-in 200ms ease-out both; }
}
CSS

How each one works:

  • Selected slot. transition: none makes the tick appear at once. It is feedback on the patient's own tap, so it needs no help to be noticed.
  • Notice banner. The banner reports something the patient did not do, so it keeps a fade. Changing opacity is not movement, and it is rarely what makes people unwell.
  • Booked tick. A fade replaces the pop. @keyframes fade-in with only a from stop animates to the element's own opacity, which is 1.

The banner and Booked tick rules have the same selectors as the full versions and come later in the file, so they win. For the slot, transition: none wins because it is the only transition rule for .slot .tick and comes last; the checked tick still ends at full size from the earlier .slot:has(input:checked) .tick rule, which is more specific. You may see a different pattern elsewhere: a global rule that sets every animation-duration and transition-duration to almost zero with !important. It is a useful safety net for a site full of third-party CSS, but it removes the fades too, and a version that uses animation: none instead of a tiny duration stops animationend events, which some scripts wait for. Writing a reduced version for each animation is more work and gives patients a better result.

Some teams turn the logic around and put the full motion inside @media (prefers-reduced-motion: no-preference), so a browser that cannot tell gets no motion. Either way is fine, as long as each animation has a deliberate reduced version.

Check it worked

Turn on reduced motion and repeat the three actions. To turn it on for the whole device: on macOS it is System Settings, Accessibility, Display, Reduce motion; on iPhone and iPad, Settings, Accessibility, Motion, Reduce Motion; on Windows 11, Settings, Accessibility, Visual effects, Animation effects (off); on Android, Settings, Accessibility, Remove animations (the exact path varies by phone maker). To change only one browser tab in Chrome or Edge, open DevTools, press Ctrl+Shift+P (Cmd+Shift+P on macOS), type "rendering", open the Rendering panel and set "Emulate CSS media feature prefers-reduced-motion" to reduce.

Reload. The 10:30 tick appears with no growth or bounce. The notice banner fades in without dropping. The Booked tick fades in without changing size. Every end state is the same as before: the same colours, the same tick, the same text. Turn the setting off again when you are done.

Step 7 · Test both versions with Playwright

A reduced-motion version is easy to break months later by adding a new animation and forgetting its pair. A test that runs the flow twice, once with each preference, catches that. Install Playwright, which drives a real browser from a script. --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password:

Bash
cd ~/larkfield-motion-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromium

Playwright's reducedMotion option sets prefers-reduced-motion for a browser context, as the operating system setting would. The test reads the animations each element is running with getAnimations(), a standard browser API, right after each action. It checks that only transform and opacity are ever animated, that full motion really moves, that reduced motion never does, and that every element ends fully visible either way.

Bash
cd ~/larkfield-motion-demo
cat > test-motion.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';

const url = new URL('./index.html', import.meta.url).href;
const browser = await chromium.launch();

// Added to every page as window.describe: what is animating on one element, right now.
function describe(selector) {
  const el = document.querySelector(selector);
  const anims = el.getAnimations();
  const props = new Set();
  for (const a of anims) {
    for (const frame of a.effect.getKeyframes()) {
      for (const key of Object.keys(frame)) {
        if (!['offset', 'computedOffset', 'easing', 'composite'].includes(key)) props.add(key);
      }
    }
  }
  return {
    names: anims.map((a) => a.animationName ?? a.transitionProperty),
    props: [...props].sort(),
  };
}

// Waits for an element's animations to finish and returns where it ended.
async function endState(page, selector) {
  return page.evaluate(async (s) => {
    const el = document.querySelector(s);
    await Promise.all(el.getAnimations().map((a) => a.finished));
    const st = getComputedStyle(el);
    return { opacity: st.opacity, transform: st.transform };
  }, selector);
}

function assertOnlyCheapProps(result, label) {
  const other = result.props.filter((p) => p !== 'opacity' && p !== 'transform');
  assert.deepEqual(other, [], `${label} animates only transform and opacity`);
}

function assertSettled(state, label) {
  assert.equal(state.opacity, '1', `${label} ends fully visible`);
  assert.ok(['none', 'matrix(1, 0, 0, 1, 0, 0)'].includes(state.transform), `${label} ends at full size, in place`);
}

for (const mode of ['no-preference', 'reduce']) {
  const reduced = mode === 'reduce';
  const context = await browser.newContext({ reducedMotion: mode, viewport: { width: 390, height: 844 } });
  await context.addInitScript(`window.describe = ${describe}`);
  const page = await context.newPage();
  await page.goto(url);
  assert.equal(await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches), reduced);

  // 1. Selected slot
  const slot = await page.evaluate(() => {
    // Read the tick's style first, so the browser has a before-change style to transition from.
    getComputedStyle(document.querySelector('.slot:has(input[value="10:30"]) .tick')).opacity;
    document.querySelector('input[value="10:30"]').click();
    return window.describe('.slot:has(input[value="10:30"]) .tick');
  });
  assertOnlyCheapProps(slot, 'slot tick');
  if (reduced) assert.deepEqual(slot.names, [], 'reduced: the slot tick appears at once');
  else assert.deepEqual(slot.names.sort(), ['opacity', 'transform'], 'full: the slot tick fades and grows');
  assertSettled(await endState(page, '.slot:has(input[value="10:30"]) .tick'), 'slot tick');

  // 3. Booked tick, after booking 10:30
  const booked = await page.evaluate(() => {
    document.querySelector('#book').click();
    return window.describe('.booked-tick');
  });
  assertOnlyCheapProps(booked, 'booked tick');
  assert.deepEqual(booked.names, [reduced ? 'fade-in' : 'tick-pop']);
  assert.equal(booked.props.includes('transform'), !reduced, reduced ? 'reduced: no scaling' : 'full: the tick scales');
  assertSettled(await endState(page, '.booked-tick'), 'booked tick');
  assert.equal(await page.evaluate(() => document.activeElement.textContent), "You're booked");
  assert.equal(await page.locator('#booked .time').textContent(), 'Tuesday 9 December, 10:30');

  // 2. Notice banner, on a fresh page
  await page.reload();
  const notice = await page.evaluate(() => {
    document.querySelector('#simulate-taken').click();
    return window.describe('.banner.notice');
  });
  assertOnlyCheapProps(notice, 'notice banner');
  assert.deepEqual(notice.names, [reduced ? 'fade-in' : 'banner-in']);
  assert.equal(notice.props.includes('transform'), !reduced, reduced ? 'reduced: no sliding' : 'full: the banner slides');
  assertSettled(await endState(page, '.banner.notice'), 'notice banner');
  assert.equal(await page.getByRole('status').textContent(), '10:30 was just taken. These times are still free.');
  assert.ok(await page.getByRole('radio', { name: '10:30' }).isDisabled());

  console.log(`PASS ${mode}: slot [${slot.names}], banner [${notice.names}], booked [${booked.names}]`);
  await context.close();
}

await browser.close();
JS
node test-motion.mjs

Each check calls click() and getAnimations() in the same evaluate, so the test reads the animation the instant it starts, with no waiting and no timing guesses. getAnimations() makes the browser apply the new styles first, which is what creates the transition or animation. The slot check reads the tick's computed style before the click, because a transition needs a style to start from; without that read, a page that has not been styled since loading might start no transition at all. A transition reports the property it animates (opacity, transform), and a keyframe animation reports its @keyframes name.

Check it worked

The output ends with two lines:

Text
PASS no-preference: slot [opacity,transform], banner [banner-in], booked [tick-pop]
PASS reduce: slot [], banner [fade-in], booked [fade-in]

To see the test fail for the right reason, delete the line .booked-tick { animation: fade-in 200ms ease-out both; } from motion.css and run node test-motion.mjs again. It stops with an AssertionError, because under reduced motion the Booked tick runs tick-pop again. Put the line back and the test passes.

Step 8 · Clean up

Remove the demo folder, which also removes the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes it if you no longer need it.

Bash
cd ~
rm -rf ~/larkfield-motion-demo

Check it worked

ls ~/larkfield-motion-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.