| | |

Svelte 39 🧡 Keyframe CSS Animations — svelte/animate and flip

⏱️ Estimated read: 7 min | |

Animating elements within a list as they change order is a classic challenge in web development. When an item is inserted, removed, or moved, the browser forces a layout reflow, causing elements to “jump” instantly to their new positions. The svelte/animate module, specifically the flip (First, Last, Invert, Play) animation, solves this by automatically calculating the element’s start and end positions and smoothly interpolating between them, creating a seamless visual transition.

This chapter covers the flip directive, the structural requirements for using it within {#each} blocks, and the configuration options that control the look and feel of list transitions. We will explore why list reordering is physically difficult for browsers to animate and how Svelte’s FLIP implementation abstracts the complex coordinate math away from the developer.

Key point: The animate:flip directive uses the FLIP technique to track the position of list items before and after a reorder, applying an animation that smoothly moves each element to its new index, provided the {#each} block uses a unique key.


Why flip exists

The layout-shift problem.

When an array is sorted or filtered, elements shift positions instantly. This jarring layout shift disrupts user focus, making it hard to track what happened to specific items in the list.

The coordinate math complexity.

Calculating the delta between an element’s “First” (start) position and its “Last” (end) position requires measuring DOM nodes precisely. FLIP automates this process so you don’t have to write manual getBoundingClientRect() loops.

The CSS animation limitation.

CSS transitions work well for property changes (like color or opacity), but they cannot natively “know” that an element has moved from index 0 to index 5 in a list. FLIP provides the missing link for geometric transitions.

The {#each} integration.

Svelte’s animate: directive is designed specifically to hook into the {#each} block’s reconciliation process, ensuring that the animation triggers exactly when the DOM nodes are re-ordered.

Performance overhead mitigation.

By calculating positions only when the order changes, flip minimizes the animation workload, keeping the UI fluid even with large lists.


a. The FLIP animation mechanics

FLIP is an acronym that describes the four stages of the transition: First (record the starting geometry), Last (record the ending geometry), Invert (use a transform to make the element look like it’s still at the start), and Play (animate the transform to zero). Svelte’s animate:flip directive executes this cycle automatically.

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

The directive requires a keyed {#each} block (e.g., (item.id)). The key is the unique identifier that Svelte uses to track which item is which, even after the array has been scrambled. Without the key, Svelte cannot distinguish between items, and the animation will fail.

b. Implementation in {#each} blocks

The animate: directive is restricted to elements that are direct children of an {#each} block. This is because the reconciliation logic is tied to the array’s index and value changes. When the array is mutated, Svelte re-renders the block and triggers the animation for any element that has changed its index.

<script>
  let items = [{id: 1, name: 'A'}, {id: 2, name: 'B'}];
  function shuffle() {
    items = [...items].sort(() => Math.random() - 0.5);
  }
</script>

<button on:click={shuffle}>Shuffle</button>

{#each items as item (item.id)}
  <div animate:flip>{item.name}</div>
{/each}

The animation runs only on elements that exist both before and after the change. Elements being removed or added are handled separately by transition: or in: / out: directives; animate: is strictly for moving items that are staying in the list.

c. Animation timing and easing

While flip works out of the box, you can customize the timing with a duration (in milliseconds) or a custom easing function from svelte/easing. This allows you to match the animation feel to your brand identity, such as using elastic for a playful feel or cubicOut for a professional interface.

<script>
  import { cubicOut } from 'svelte/easing';
</script>

<div animate:flip={{ duration: 500, easing: cubicOut }}>
  Slow, smooth reordering.
</div>

Increasing the duration makes the reordering process more explicit, which can be helpful in complex interfaces where the user needs to follow the movement. Keeping it short (under 300ms) keeps the app feeling snappy.


Complete Example Session

// ============================================
// PART 1: KEYED EACH BLOCK
// ============================================
{#each items as item (item.id)}
  <div animate:flip>{item.val}</div>
{/each}

// ============================================
// PART 2: DURATION CUSTOMIZATION
// ============================================
<div animate:flip={{ duration: 400 }}>...</div>

// ============================================
// PART 3: EASING FUNCTIONS
// ============================================
<script>
  import { backOut } from 'svelte/easing';
</script>
<div animate:flip={{ easing: backOut }}>...</div>

// ============================================
// PART 4: INTEGRATING TRANSITIONS
// ============================================
{#each items as item (item.id)}
  <div transition:fade animate:flip>{item.val}</div>
{/each}

This sequence shows the fundamental keying, timing customization, adding easing effects, and combining reorder animations with entry/exit fades.


Quick Reference

The animate:flip API

OptionTypeDefault
durationnumber / function300ms
easingfunctioncubicOut

Constraints

ConstraintReason
Must use {#each}Directive needs array index
Must use key (item.id)Svelte needs to map nodes
Direct child onlyFLIP logic needs parent context

Best Practices

✅ Do This:

// Always key your each blocks
{#each list as item (item.id)} ... {/each}               // ✅

// Mix with transitions for best UX
<div transition:fade animate:flip> ... </div>             // ✅

// Use standard durations for consistency
<div animate:flip={{ duration: 250 }} />                 // ✅

// Use easing for professional feel
<div animate:flip={{ easing: quintOut }} />              // ✅

❌ Don’t Do This:

// Forget the key
{#each list as item} ... {/each}                        // ❌

// Use animate outside an each block
<div animate:flip />                                    // ❌

// Use extremely long durations
<div animate:flip={{ duration: 2000 }} />               // ❌

Common Pitfalls

PitfallWhy It HappensFix
No animationMissing key (item.id)Add unique key
Jumpy UIOverlapping transitionsUse proper transitions
Performance hitToo many itemsAdd animate:flip only to root
Broken animationNon-direct childMove directive to child

Real-World Examples

1. Sortable Kanban Board

{#each tasks as task (task.id)}
  <div animate:flip>{task.title}</div>
{/each}

2. Dynamic Shopping Cart

{#each cart as item (item.sku)}
  <div animate:flip>{item.name}</div>
{/each}

3. Data Visualization Updates

{#each bars as bar (bar.label)}
  <div animate:flip>{bar.value}</div>
{/each}

4. Filtered List

{#each filtered as item (item.id)}
  <li animate:flip>{item.text}</li>
{/each}

5. Playlist Shuffling

{#each tracks as t (t.id)}
  <div animate:flip>{t.name}</div>
{/each}

6. Leaderboard Update

{#each players as p (p.rank)}
  <div animate:flip>{p.name}</div>
{/each}

7. Tag Cloud

{#each tags as tag (tag.id)}
  <span animate:flip>{tag.name}</span>
{/each}

8. Messaging History

{#each msgs as m (m.id)}
  <div animate:flip>{m.text}</div>
{/each}

9. Dashboard Tiles

{#each tiles as t (t.id)}
  <div animate:flip>{t.label}</div>
{/each}

10. Todo List Priority

{#each todos as t (t.id)}
  <div animate:flip>{t.task}</div>
{/each}

Visual

The FLIP Cycle

┌──────────────────────────────────────────────┐
│  First:  Record Start Position (X1, Y1)      │
│  Last:   Record End Position   (X2, Y2)      │
│  Invert: Apply Transform (dx, dy)            │
│  Play:   Animate Transform to (0, 0)         │
└──────────────────────────────────────────────┘

Reorder Flow

┌──────────────────────────────────────────────┐
│  BEFORE SHUFFLE         AFTER SHUFFLE        │
│  [A] (0,0)              [C] (0,0)            │
│  [B] (0,50)             [A] (0,50)           │
│  [C] (0,100)            [B] (0,100)          │
│                                              │
│  FLIP detects change, animates [A] to 50px   │
└──────────────────────────────────────────────┘

Summary

ItemValue
Directiveanimate:flip
TechniqueFLIP
RequirementKeyed {#each} block
Dependencysvelte/animate
TimingConfigurable

Key takeaways:

  • FLIP automates movement. It handles the coordinate calculation required to animate list reordering, turning a complex layout problem into a single directive.
  • Keys are mandatory. The {#each} block must have a key, as it provides the stable identity Svelte needs to track nodes across reorders.
  • Integrate with transitions. Use animate:flip for movement and transition:fade for entry/exit to create polished, professional UI interactions.
  • Customize with easing. Easing functions significantly affect the “personality” of your list animations; choose them to match your app’s tone.
  • Keep it direct. The directive must be applied to a direct child of the {#each} block to function correctly within the reconciliation process.

Remember: List animations are a hallmark of high-quality web applications. By using animate:flip, you leverage the FLIP technique to provide users with clear visual feedback about how list items change, making your application feel faster, more responsive, and easier to navigate.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!