Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 35 ยท Motion and Polish

Transitions and In/Out Animations

Learn Svelte transitions: transition:fade, in: and out:, built-in fly, slide and scale effects, easing, local vs global, events and writing your own.

A UI that jumps is harder to follow than one that moves. When a panel opens, a toast appears or a list item is deleted, a short transition tells the eye what just happened. Svelte makes this a one-word feature: add transition:fade to an element and it fades in when it is created and fades out when it is removed.

This lesson covers the transition:, in: and out: directives, the built-in effects from svelte/transition, easing, parameters, local versus global behavior, transition events and how to write your own transition function.

The Svelte compiler cannot run on this site, so the Svelte code below is read-only. The runnable <TryIt> blocks are stand-ins: plain JavaScript that reproduces the maths a transition runs, so you can see what Svelte actually does with your parameters.

The transition directive

Import an effect and attach it to an element that lives inside an {#if}, {#each}, {#key} or {#await} block:

HTML
<script>
  import { fade } from 'svelte/transition';

  let visible = $state(true);
</script>

<button onclick={() => (visible = !visible)}>Toggle</button>

{#if visible}
  <p transition:fade>Hello, I fade in and out.</p>
{/if}

When visible becomes false, Svelte does not remove the <p> at once. It keeps it in the DOM, plays the outro, and removes it when the animation ends. When visible becomes true, it creates the element and plays the intro.

transition: is bidirectional: the same effect runs forward for the intro and backward for the outro. If the user toggles quickly, a half-finished intro simply reverses from where it was, with no jump.

in: and out: for separate effects

Use in: and out: when the entrance and exit should differ. Unlike transition:, they are not reversible: an interrupted outro does not rewind, a new intro starts alongside it.

HTML
<script>
  import { fly, fade } from 'svelte/transition';
  let open = $state(false);
</script>

{#if open}
  <aside in:fly={{ x: -200, duration: 300 }} out:fade={{ duration: 150 }}>
    Menu
  </aside>
{/if}

Slide in from the left, fade away quickly: a common pattern for drawers and toasts.

Built-in transitions

svelte/transition ships a small set of effects:

Function What it does Useful parameters
fade Animates opacity delay, duration, easing
blur Blurs and fades amount, opacity
fly Moves from an offset and fades x, y, opacity
slide Collapses height (or width) axis
scale Scales and fades start, opacity
draw Draws an SVG path stroke speed or duration
crossfade Pairs elements that move between two places covered in Flip and Crossfade

Every one accepts delay (milliseconds before it starts), duration (how long it runs) and easing (a function from svelte/easing, such as cubicOut, elasticOut, quintInOut). Pass parameters as an object inside a second pair of braces: transition:fly={{ y: 20, duration: 250 }}.

slide is the right choice for accordions and collapsing sections, because it animates the real height. A fly on tall content looks heavy; keep distances small (10 to 30 px) for subtle UI.

What a transition really is

A transition is a function. It receives the DOM node, your parameters and some extra info, and returns an object describing the animation. The most important key is css, a function of t (progress from 0 to 1) that returns a CSS string for that moment. Svelte turns it into a real CSS animation (running on the compositor, off the JavaScript thread) rather than updating styles from JavaScript each frame.

During an intro, t goes from 0 to 1. During an outro, it goes from 1 to 0. u is just 1 - t, passed for convenience.

This stand-in builds the same sampled keyframes that fade and fly would, so you can see the numbers:

JS Sampling a transition's css(t, u) function

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

No output.

At 0% the element is fully transparent and 20 px lower; at 100% it sits at rest. Because cubicOut starts fast and slows down, most of the movement happens early, which feels natural for things arriving on screen.

Local versus global transitions

In Svelte 5, transitions are local by default: they play only when the block they are directly inside is created or destroyed, not when a parent block changes. That prevents a flurry of animations when a whole section disappears.

HTML
{#if showList}
  <ul>
    {#each items as item (item.id)}
      <!-- plays when an item is added or removed, but NOT when showList flips -->
      <li transition:slide>{item.name}</li>
    {/each}
  </ul>
{/if}

If you want an item to animate when an ancestor block toggles as well, mark it |global: transition:slide|global.

Transition events

Four events tell you when animations start and end. Use them to disable interactions or to clean up:

HTML
<p
  transition:fade
  onintrostart={() => (busy = true)}
  onintroend={() => (busy = false)}
  onoutrostart={() => console.log('leaving')}
  onoutroend={() => console.log('gone')}
>
  Saved!
</p>

Writing your own transition

Return a css function for transforms and opacity (preferred, GPU-friendly) or a tick function for things CSS cannot express, such as changing text. A typewriter effect is the classic tick example:

HTML
<script>
  function typewriter(node, { speed = 1 }) {
    const text = node.textContent;
    const duration = text.length / (speed * 0.01);

    return {
      duration,
      tick: (t) => {
        node.textContent = text.slice(0, Math.trunc(text.length * t));
      },
    };
  }
</script>

{#if visible}
  <p transition:typewriter>The quick brown fox</p>
{/if}

Svelte calls tick(t, u) on every animation frame. Here is the same function driven by a tiny fake clock, so you can watch each call:

JS A custom tick transition, driven by a fake clock

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

No output.

The function reads the original text once, then slices a longer prefix on every tick. Because tick runs on the main thread, prefer css whenever a visual effect can be expressed with it.

Accessibility and motion

Some people feel sick from large movements. Respect prefers-reduced-motion: in Svelte 5 you can import prefersReducedMotion from svelte/motion and set duration to 0 when it is true. Keep transitions short (150 to 300 ms); long ones make an app feel slow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does transition:fade do on an element inside an {#if} block?

    Svelte keeps the node in the DOM during the outro, then removes it. The same effect plays forward on creation and backward on removal.
  2. 2. What is the difference between transition: and in:/out:?

    A transition: directive can reverse mid-way if the block toggles quickly. in: and out: are separate animations and do not reverse.
  3. 3. In Svelte 5, when does a plain transition: on a list item play?

    Transitions are local by default. Add |global to make them play when a parent block toggles too.
  4. 4. Which key of a custom transition's return object is preferred for visual effects?

    css is turned into a real CSS animation that can run off the main thread. tick runs in JavaScript each frame and is for effects CSS cannot express, like changing text.

Summary

  • transition:fn animates an element in and out of {#if}, {#each}, {#key} and {#await} blocks; in: and out: use separate effects.
  • Built-ins live in svelte/transition (fade, fly, slide, scale, blur, draw); parameters go in {{ }}; easing comes from svelte/easing.
  • Transitions are local by default in Svelte 5; add |global to animate with ancestor blocks.
  • A transition is a function returning duration, easing and css(t, u) or tick(t, u).
  • Respect reduced-motion preferences and keep animations short.

Next: Flip and Crossfade