Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 35 ยท Motion and Polish

Animating Lists with animate:flip and crossfade

Animate reordered lists with animate:flip, move items between lists with crossfade, learn the FLIP technique, keyed each requirements and custom animate functions.

Transitions handle elements that appear and disappear. But what about elements that move? When you sort a table, delete a row from the middle of a list or drag a card from "To do" to "Done", the other items snap to their new positions. Svelte has two tools to smooth that out: animate:flip for items that shift within one list, and crossfade for items that travel between two.

The compiler is not available on this site, so Svelte syntax is shown read-only. The <TryIt> blocks are stand-ins in plain JavaScript that compute the same numbers Svelte uses.

What FLIP means

FLIP stands for First, Last, Invert, Play. It is a technique for animating layout changes cheaply:

  1. First: record where each element is now.
  2. Last: let the DOM update, then record where each element ended up.
  3. Invert: apply a transform that moves each element back to where it was, so visually nothing changed.
  4. Play: remove the transform gradually, so the element glides to its new position.

Only transform animates, so the browser never recomputes layout during the animation. Svelte's animate:flip does these four steps for you.

flowchart LR
  A["First: measure old rect"] --> B["Last: DOM updates, measure new rect"]
  B --> C["Invert: translate by the difference"]
  C --> D["Play: animate transform to zero"]

FLIP animates only a transform, which is cheap.

animate:flip in practice

Import flip from svelte/animate and put animate:flip on the immediate child of a keyed {#each} block:

HTML
<script>
  import { flip } from 'svelte/animate';

  let items = $state([
    { id: 1, name: 'Apples' },
    { id: 2, name: 'Bananas' },
    { id: 3, name: 'Cherries' },
  ]);

  function shuffle() {
    items = items.toSorted(() => Math.random() - 0.5);
  }
</script>

<button onclick={shuffle}>Shuffle</button>

<ul>
  {#each items as item (item.id)}
    <li animate:flip={{ duration: 300 }}>{item.name}</li>
  {/each}
</ul>

Two rules matter:

  • The each block must be keyed ((item.id)). Without keys, Svelte reuses DOM nodes by position and nothing really "moves".
  • animate: must sit on the element that is the direct child of the each block, not on something nested inside it.

flip accepts delay, duration (a number or a function of the distance, (d) => Math.sqrt(d) * 120) and easing. Combine it with transitions on the same element so additions fade in while neighbors slide aside:

HTML
<li in:fade out:fade animate:flip>{item.name}</li>

The numbers behind it

Here is the invert step in plain JavaScript. Each item has an old and a new vertical position; FLIP computes the starting transform and then interpolates it to zero.

JS FLIP: invert, then play

Press Run (or Ctrl + Enter) to see the console output here.

No output.

C moved from the bottom to the top, so it starts 80 px below its final place and glides up, while A and B start 40 px higher and glide down. Nothing ever jumps because the first frame looks exactly like the old layout.

crossfade: moving between lists

animate:flip only works inside one each block. For a todo app with two columns, an item that leaves list A and enters list B is two different elements: one is removed, one is created. crossfade pairs them up. It returns two transitions, conventionally named send and receive:

HTML
<script>
  import { crossfade } from 'svelte/transition';
  import { flip } from 'svelte/animate';
  import { quintOut } from 'svelte/easing';

  const [send, receive] = crossfade({
    duration: 300,
    easing: quintOut,
    fallback(node) {
      // used when there is no matching partner
      return { duration: 200, css: (t) => `opacity: ${t}` };
    },
  });

  let todos = $state([
    { id: 1, text: 'Write lesson', done: false },
    { id: 2, text: 'Read docs', done: true },
  ]);
</script>

<div class="columns">
  <section>
    <h2>To do</h2>
    {#each todos.filter((t) => !t.done) as todo (todo.id)}
      <label in:receive={{ key: todo.id }} out:send={{ key: todo.id }} animate:flip>
        <input type="checkbox" bind:checked={todo.done} /> {todo.text}
      </label>
    {/each}
  </section>

  <section>
    <h2>Done</h2>
    {#each todos.filter((t) => t.done) as todo (todo.id)}
      <label in:receive={{ key: todo.id }} out:send={{ key: todo.id }} animate:flip>
        <input type="checkbox" bind:checked={todo.done} /> {todo.text}
      </label>
    {/each}
  </section>
</div>

The key ties the two ends together. When todo 1 is ticked, it is sent from the first list at the same moment the second list receives an element with the same key. crossfade measures where the old element was and starts the new one there, so the card visibly flies from one column to the other. If no partner exists (a brand-new item), the fallback runs instead.

Both lists keep animate:flip so the other items close the gap smoothly.

How the pairing works

Inside, crossfade keeps two maps keyed by your key: elements about to leave and elements about to arrive. This stand-in reproduces the matchmaking:

JS crossfade: pairing send and receive by key

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real implementation also handles timing and the actual CSS, but the idea is exactly this: the first side to run records its position, the second side finds it and animates from there.

Custom animate functions

Like transitions, an animate: function can be your own. It receives the node, { from, to } rectangles and your parameters, and returns delay, duration, easing, css or tick:

HTML
<script>
  function glide(node, { from, to }, { duration = 250 } = {}) {
    const dx = from.left - to.left;
    const dy = from.top - to.top;
    return {
      duration,
      css: (t, u) => `transform: translate(${u * dx}px, ${u * dy}px)`,
    };
  }
</script>

<li animate:glide>{item.name}</li>

Common mistakes

  • Forgetting the key in {#each ... (item.id)}: items reuse nodes and nothing animates.
  • Putting animate: on a nested element instead of the direct child.
  • Using the array index as key. When items reorder, an index key changes meaning; use a stable id.
  • Using different key values on in:receive and out:send: they never pair up.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does FLIP stand for?

    You measure the first position, measure the last position, invert with a transform so nothing seems to move, then play by removing the transform gradually.
  2. 2. What must be true for animate:flip to work?

    Without keys Svelte reuses nodes by position, so nothing moves; and animate: only applies to the immediate child of a keyed each block.
  3. 3. What does the key option in crossfade's send and receive do?

    Matching keys let crossfade start the arriving element at the leaving element's position.
  4. 4. When does crossfade's fallback run?

    An element with no counterpart (a brand-new or fully removed item) uses the fallback transition instead of flying.

Summary

  • Use animate:flip (from svelte/animate) to smooth items that shift inside one keyed each block; it implements the FLIP technique with transforms only.
  • crossfade returns [send, receive]; give both the same key so an element appears to travel between two lists.
  • The animate: directive goes on the direct child of a keyed each block, and keys must be stable ids.
  • You can write your own animate function returning css or tick.

Next: Tween and Spring