<!-- Source: https://motion.svelte.page/examples/animate-layout -->

# animateLayout

> Layout animations on plain elements with animateLayout — a switch knob, a shared tab underline, and a shuffled grid, no motion components.

**Source:** [https://motion.svelte.page/examples/animate-layout](https://motion.svelte.page/examples/animate-layout)

**Markdown mirror:** [https://motion.svelte.page/examples/animate-layout.md](https://motion.svelte.page/examples/animate-layout.md)

---

This mirror preserves the prose, implementation notes, and runnable Svelte source behind the live example page.

## FIG-001: a switch knob on data-layout.

The knob is a plain element tagged data-layout. Flipping the switch changes justify-content inside animateLayout, and the knob springs from its old position to its new one.

**Metadata:** tag: `POSITION` | attr: `data-layout`

### Notes

- `animateLayout(update)` measures every tagged element, runs the update — Svelte `$state` mutations are flushed synchronously, so plain assignment works — then animates each element from its old box to its new one.
- The knob only moves, so `data-layout` and `data-layout="position"` look identical here. Use `"position"` or `"size"` to animate one axis of the change and snap the other.
- Clicking again mid-flight interrupts the spring and continues from the knob's current position — no jump back to the start.

### Source

#### ToggleSwitch.svelte

Source file: [src/lib/examples/animate-layout/demos/ToggleSwitch.svelte](https://github.com/humanspeak/svelte-motion/blob/main/docs/src/lib/examples/animate-layout/demos/ToggleSwitch.svelte)

```svelte
<script lang="ts">
    import { animateLayout } from '@humanspeak/svelte-motion'

    // A switch knob on a plain <div data-layout>. The state flip moves the
    // knob with justify-content; animateLayout measures it before and after
    // the update and springs it between the two boxes. No motion component.

    let on = $state(false)
    let root = $state<HTMLElement | null>(null)

    const toggle = () => {
        if (!root) return
        // Scoped to this demo so other tagged elements on the page stay put.
        animateLayout(
            root,
            () => {
                on = !on
            },
            {
                type: 'spring',
                visualDuration: 0.35,
                bounce: 0.25
            }
        )
    }
</script>

<!-- dk-strip: docs-kit positioning shell — stripped from the published code. -->
<div class="dk-demo-shell">
    <div class="strip" bind:this={root}>
        <div class="strip-head">
            <span class="micro">// toggle switch</span>
            <span class="micro readout">state · {on ? 'on' : 'off'}</span>
        </div>

        <div class="stage">
            <button
                type="button"
                class="switch"
                class:on
                role="switch"
                aria-checked={on}
                aria-label="Toggle"
                onclick={toggle}
            >
                <span class="knob" data-layout></span>
            </button>
        </div>

        <div class="strip-foot">
            <span class="micro">attr: data-layout</span>
            <span class="micro">update: on = !on</span>
        </div>
    </div>
</div>

<style>
    .dk-demo-shell {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1.5rem;
        min-height: 400px;
    }

    .strip {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
        width: min(100%, 360px);
    }

    .micro {
        font-family: var(--brut-mono, monospace);
        font-size: 0.6875rem;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        color: var(--brut-ink-3, #9a9a9a);
    }

    .strip-head,
    .strip-foot {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        border-bottom: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-bottom: 0.5rem;
    }

    .strip-foot {
        border-bottom: none;
        border-top: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-top: 0.75rem;
        padding-bottom: 0;
    }

    .readout {
        color: var(--brut-accent, #247768);
    }

    .stage {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 200px;
    }

    /* The layout change itself: justify-content flips the knob's side. */
    .switch {
        display: flex;
        justify-content: flex-start;
        box-sizing: border-box;
        width: 128px;
        height: 64px;
        padding: 8px;
        border: 1px solid var(--brut-ink, #0a0a0a);
        border-radius: 0;
        background: var(--brut-bg, #f8fcfb);
        cursor: pointer;
        transition: background-color 0.25s;
    }

    .switch.on {
        justify-content: flex-end;
        background: var(--brut-accent, #247768);
    }

    .knob {
        display: block;
        box-sizing: border-box;
        width: 46px;
        height: 46px;
        border: 1px solid var(--brut-ink, #0a0a0a);
        background: var(--brut-ink, #0a0a0a);
    }

    .switch.on .knob {
        background: var(--brut-bg, #f8fcfb);
    }
</style>
```

## FIG-002: a tab underline that travels.

Only the selected tab renders the highlight and underline. Elements sharing a data-layout-id hand off across the update, and .shared() gives the underline a springier transition than the highlight.

**Metadata:** tag: `SHARED` | attr: `data-layout-id`

### Notes

- Svelte removes the old highlight and underline and mounts new ones under the selected tab. Because they share a `data-layout-id`, each new element animates from the old one's position and size.
- `.shared('tab-underline', transition)` overrides the transition for one id — the underline springs while the highlight uses the default 0.25s ease.
- Both elements have square corners: plain elements have no tracked `border-radius`, so a rounded element that changes size would stretch its corners mid-animation.

### Source

#### SharedUnderlineTabs.svelte

Source file: [src/lib/examples/animate-layout/demos/SharedUnderlineTabs.svelte](https://github.com/humanspeak/svelte-motion/blob/main/docs/src/lib/examples/animate-layout/demos/SharedUnderlineTabs.svelte)

```svelte
<script lang="ts">
    import { animateLayout } from '@humanspeak/svelte-motion'

    // Shared-element handoff on plain elements: only the selected tab
    // renders the highlight and the underline. Selecting another tab
    // removes them from one tab and mounts new ones in another; elements
    // that share a data-layout-id animate from the old element's box.
    // .shared() gives the underline its own springier transition.

    const tabs = ['Overview', 'API', 'Examples', 'FAQ'] as const
    type Tab = (typeof tabs)[number]

    let selected = $state<Tab>('Overview')
    let root = $state<HTMLElement | null>(null)

    const select = (tab: Tab) => {
        if (!root || tab === selected) return
        animateLayout(
            root,
            () => {
                selected = tab
            },
            { duration: 0.25, ease: 'easeOut' }
        ).shared('tab-underline', { type: 'spring', visualDuration: 0.45, bounce: 0.35 })
    }
</script>

<!-- dk-strip: docs-kit positioning shell — stripped from the published code. -->
<div class="dk-demo-shell">
    <div class="strip" bind:this={root}>
        <div class="strip-head">
            <span class="micro">// shared underline</span>
            <span class="micro readout">tab · {selected.toLowerCase()}</span>
        </div>

        <div class="stage">
            <div class="tabs" role="tablist">
                {#each tabs as tab (tab)}
                    <button
                        type="button"
                        role="tab"
                        class="tab"
                        class:selected={selected === tab}
                        aria-selected={selected === tab}
                        onclick={() => select(tab)}
                    >
                        {#if selected === tab}
                            <span class="highlight" data-layout-id="tab-highlight"></span>
                            <span class="underline" data-layout-id="tab-underline"></span>
                        {/if}
                        <span class="label">{tab}</span>
                    </button>
                {/each}
            </div>
        </div>

        <div class="strip-foot">
            <span class="micro">attr: data-layout-id</span>
            <span class="micro">.shared('tab-underline')</span>
        </div>
    </div>
</div>

<style>
    .dk-demo-shell {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1.5rem;
        min-height: 400px;
    }

    .strip {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }

    .micro {
        font-family: var(--brut-mono, monospace);
        font-size: 0.6875rem;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        color: var(--brut-ink-3, #9a9a9a);
    }

    .strip-head,
    .strip-foot {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        border-bottom: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-bottom: 0.5rem;
    }

    .strip-foot {
        border-bottom: none;
        border-top: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-top: 0.75rem;
        padding-bottom: 0;
    }

    .readout {
        color: var(--brut-accent, #247768);
    }

    .stage {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 200px;
    }

    .tabs {
        display: flex;
        border: 1px solid var(--brut-ink, #0a0a0a);
        background: var(--brut-bg, #f8fcfb);
    }

    /* Labels differ in length, so the handoff animates size as well as
       position. */
    .tab {
        position: relative;
        padding: 0.875rem 1.125rem;
        border: none;
        background: none;
        color: var(--brut-ink-2, #525252);
        font-family: var(--brut-mono, monospace);
        font-size: 0.75rem;
        letter-spacing: 0.06em;
        text-transform: uppercase;
        cursor: pointer;
    }

    .tab.selected {
        color: var(--brut-ink, #0a0a0a);
    }

    .label {
        position: relative;
    }

    /* Square corners: scaling a plain element stretches any border
       radius, and a hard 0 has nothing to distort. */
    .highlight {
        position: absolute;
        inset: 0;
        background: var(--brut-accent-soft, rgba(36, 119, 104, 0.1));
    }

    .underline {
        position: absolute;
        right: 0;
        bottom: 0;
        left: 0;
        height: 3px;
        background: var(--brut-accent, #247768);
    }
</style>
```

## FIG-003: shuffling a keyed grid.

Reordering a keyed each block moves the existing tile nodes; animateLayout, scoped to the grid, slides every tile from its old slot to its new one.

**Metadata:** tag: `REORDER` | scope: `grid`

### Notes

- A keyed `each` block reorders the existing DOM nodes instead of recreating them, so each tile keeps its identity and animates between grid slots.
- Passing the grid as the first argument scopes the call: only tagged elements inside it are measured, so the other demos on this page never animate from a shuffle.

### Source

#### ShuffleGrid.svelte

Source file: [src/lib/examples/animate-layout/demos/ShuffleGrid.svelte](https://github.com/humanspeak/svelte-motion/blob/main/docs/src/lib/examples/animate-layout/demos/ShuffleGrid.svelte)

```svelte
<script lang="ts">
    import { animateLayout } from '@humanspeak/svelte-motion'

    // Reordering a keyed {#each}: Svelte moves the existing tile nodes,
    // and animateLayout animates every <div data-layout> inside the grid
    // from its old slot to its new one. Passing the grid as the scope
    // limits the measurement to these tiles.

    const initial = Array.from({ length: 9 }, (_, index) => index + 1)

    let tiles = $state([...initial])
    let grid = $state<HTMLElement | null>(null)

    const shuffled = (list: number[]) => {
        const next = [...list]
        for (let i = next.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1))
            ;[next[i], next[j]] = [next[j], next[i]]
        }
        return next
    }

    const reorder = (next: number[]) => {
        if (!grid) return
        animateLayout(
            grid,
            () => {
                tiles = next
            },
            {
                type: 'spring',
                visualDuration: 0.5,
                bounce: 0.2
            }
        )
    }
</script>

<!-- dk-strip: docs-kit positioning shell — stripped from the published code. -->
<div class="dk-demo-shell">
    <div class="strip">
        <div class="strip-head">
            <span class="micro">// shuffle grid</span>
            <span class="micro readout">order · {tiles.join('')}</span>
        </div>

        <div class="stage">
            <div class="grid" bind:this={grid}>
                {#each tiles as tile (tile)}
                    <div class="tile" class:accent={tile % 3 === 0} data-layout>
                        {String(tile).padStart(2, '0')}
                    </div>
                {/each}
            </div>
        </div>

        <div class="controls">
            <button type="button" onclick={() => reorder(shuffled(tiles))}>Shuffle</button>
            <button type="button" onclick={() => reorder([...initial])}>Sort</button>
        </div>

        <div class="strip-foot">
            <span class="micro">scope: grid</span>
            <span class="micro">keyed each · 09 tiles</span>
        </div>
    </div>
</div>

<style>
    .dk-demo-shell {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 1.5rem;
        min-height: 400px;
    }

    .strip {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }

    .micro {
        font-family: var(--brut-mono, monospace);
        font-size: 0.6875rem;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        color: var(--brut-ink-3, #9a9a9a);
    }

    .strip-head,
    .strip-foot {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        border-bottom: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-bottom: 0.5rem;
    }

    .strip-foot {
        border-bottom: none;
        border-top: 1px dashed var(--brut-rule-2, #bbc4c0);
        padding-top: 0.75rem;
        padding-bottom: 0;
    }

    .readout {
        color: var(--brut-accent, #247768);
    }

    .stage {
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 240px;
    }

    .grid {
        display: grid;
        grid-template-columns: repeat(3, 64px);
        gap: 10px;
    }

    .tile {
        display: flex;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        width: 64px;
        height: 64px;
        border: 1px solid var(--brut-ink, #0a0a0a);
        background: var(--brut-bg, #f8fcfb);
        color: var(--brut-ink, #0a0a0a);
        font-family: var(--brut-mono, monospace);
        font-size: 0.875rem;
        font-weight: 700;
    }

    .tile.accent {
        background: var(--brut-accent, #247768);
        color: var(--brut-bg, #f8fcfb);
    }

    .controls {
        display: flex;
        justify-content: center;
        gap: 0.5rem;
    }

    .controls button {
        padding: 0.4rem 0.8rem;
        border: 1px solid var(--brut-ink, #0a0a0a);
        background: var(--brut-bg, #f8fcfb);
        color: var(--brut-ink, #0a0a0a);
        font-family: var(--brut-mono, monospace);
        font-size: 0.6875rem;
        letter-spacing: 0.08em;
        text-transform: uppercase;
        cursor: pointer;
    }
</style>
```
