How to Use In and Out Transitions in Svelte
In Svelte, use the
in: directive to animate elements when they appear and the out: directive to animate them when they disappear. You can apply built-in transitions like fade or create custom ones by importing them and adding in:fade or out:fade to your element tags.Syntax
Use in: and out: directives on HTML elements to add transitions when they enter or leave the DOM. Import transitions from svelte/transition and apply them like functions.
in:transitionNameruns when the element appears.out:transitionNameruns when the element disappears.- You can pass options to customize duration, delay, easing, etc.
svelte
import { fade, slide } from 'svelte/transition'; <!-- Element with in and out transitions --> <div in:fade={{ duration: 400 }} out:slide={{ duration: 300 }}> Content here </div>
Example
This example shows a button toggling a box that fades in when it appears and slides out when it disappears.
svelte
<script> import { fade, slide } from 'svelte/transition'; let visible = false; </script> <button on:click={() => visible = !visible} aria-pressed={visible} aria-label="Toggle box"> Toggle Box </button> {#if visible} <div in:fade={{ duration: 500 }} out:slide={{ duration: 400 }} tabindex="0" role="region" aria-live="polite" style="margin-top: 1rem; padding: 1rem; background-color: #def; border-radius: 0.5rem;"> This box fades in and slides out. </div> {/if}
Output
A button labeled 'Toggle Box'. When clicked, a blue box appears with a fade effect and disappears with a slide effect.
Common Pitfalls
Common mistakes include:
- Not importing the transition functions from
svelte/transition. - Using
in:orout:without an{#if}block, so the element never actually enters or leaves the DOM. - Forgetting to pass options as an object with curly braces, e.g.,
in:fade={{ duration: 300 }}. - Applying transitions to elements that are always present, which causes no visible effect.
svelte
/* Wrong: No import and no conditional rendering */ <div in:fade>Always here</div> /* Right: Import and conditional rendering */ <script> import { fade } from 'svelte/transition'; let show = true; </script> {#if show} <div in:fade>Appears with fade</div> {/if}
Quick Reference
| Directive | Purpose | Example Usage |
|---|---|---|
| in:transition | Animate element when it enters the DOM | ... |
| out:transition | Animate element when it leaves the DOM | ... |
| transition | Animate both in and out with same transition | ... |
| Options | Customize duration, delay, easing | ... |
Key Takeaways
Use
in: and out: directives to animate elements entering and leaving the DOM.Always import transitions like
fade or slide from svelte/transition before using them.Wrap elements with transitions inside
{#if} blocks to trigger animations on mount and unmount.Pass options as objects to control animation speed and delay, e.g.,
in:fade={{ duration: 400 }}.Avoid applying transitions to elements that never enter or leave the DOM, as no animation will show.