Custom transitions let you create smooth animations when elements appear or disappear. They make your app feel lively and polished.
Custom transitions in Svelte
import { cubicOut } from 'svelte/easing'; function customTransition(node, { duration = 400 }) { return { duration, css: t => `opacity: ${t}; transform: translateX(${(1 - t) * 100}px);`, easing: cubicOut }; }
The node is the HTML element to animate.
The function returns an object with duration, css for styles, and optional easing.
function fadeAndSlide(node, { duration = 500 }) { return { duration, css: t => `opacity: ${t}; transform: translateX(${(1 - t) * 50}px);` }; }
function scaleUp(node, { duration = 300 }) { return { duration, css: t => `transform: scale(${t}); opacity: ${t};` }; }
function bounce(node, { duration = 600 }) { return { duration, css: t => `transform: translateY(${Math.sin(t * Math.PI) * -20}px); opacity: ${t};` }; }
This Svelte component shows a green box that appears and disappears with a custom fade and slide transition. The button toggles the box. The transition moves the box from right to left while fading it in or out.
Accessibility is included with aria-pressed, aria-live, and keyboard focus.
<script> import { cubicOut } from 'svelte/easing'; import { onMount } from 'svelte'; let visible = false; function customFadeSlide(node, { duration = 400 }) { return { duration, easing: cubicOut, css: t => `opacity: ${t}; transform: translateX(${(1 - t) * 100}px);` }; } onMount(() => { visible = true; }); </script> <button on:click={() => visible = !visible} aria-pressed={visible} aria-label="Toggle box"> Toggle Box </button> {#if visible} <div transition:customFadeSlide={{ duration: 600 }} role="region" aria-live="polite" tabindex="0" style="width: 200px; height: 100px; background-color: #4caf50; color: white; display: flex; align-items: center; justify-content: center; margin-top: 1rem; border-radius: 0.5rem;" > Hello with custom transition! </div> {/if}
Custom transitions let you control exactly how elements animate.
Use css function to write styles that change over time from 0 to 1.
Remember to add accessibility attributes like aria-live and keyboard focus for dynamic content.
Custom transitions create smooth, unique animations for elements entering or leaving.
You write a function that returns styles changing over time.
They help make your app feel friendly and polished.