How to Use Fade Transition in Svelte: Simple Guide
In Svelte, use the
fade function from svelte/transition to apply a fade effect to elements. Import it and add transition:fade to the element you want to animate when it enters or leaves the DOM.Syntax
The fade transition is imported from svelte/transition. You apply it to an element using the transition:fade directive. You can optionally pass parameters like duration to control the speed.
- import: Bring in
fadefromsvelte/transition. - directive: Use
transition:fadeon the element. - parameters: Customize with options like
{ duration: 400 }.
svelte
import { fade } from 'svelte/transition'; <!-- Usage in markup --> <div transition:fade>Content</div> <!-- With options --> <div transition:fade={{ duration: 500 }}>Content</div>
Example
This example shows a button that toggles a box with a fade transition. When the box appears or disappears, it smoothly fades in or out.
svelte
<script> import { fade } 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 transition:fade={{ duration: 600 }} style="width: 200px; height: 100px; background-color: #4caf50; margin-top: 1rem; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold;"> Fading Box </div> {/if}
Output
A button labeled 'Toggle Box'. When clicked, a green box with white text 'Fading Box' smoothly fades in or out below the button.
Common Pitfalls
Common mistakes when using fade include:
- Not importing
fadefromsvelte/transition. - Using
transition:fadeon elements that never enter or leave the DOM, so no animation happens. - Forgetting to wrap the element in an
{#if}block or similar conditional to trigger the transition. - Passing options incorrectly (should be an object, e.g.,
{ duration: 300 }).
Example of wrong and right usage:
svelte
<!-- Wrong: missing import and no conditional --> <div transition:fade>Always visible</div> <!-- Right: imported fade and conditional rendering --> <script> import { fade } from 'svelte/transition'; let show = true; </script> {#if show} <div transition:fade>Visible with fade</div> {/if}
Quick Reference
Summary tips for using fade transition in Svelte:
- Always import
fadefromsvelte/transition. - Use
transition:fadeon elements that appear or disappear. - Control speed with
{ duration: milliseconds }. - Combine with
{#if}blocks for toggling visibility. - Ensure accessibility by using proper ARIA attributes on toggles.
Key Takeaways
Import fade from svelte/transition and apply with transition:fade on elements.
Use conditional rendering like {#if} to trigger fade transitions on enter/leave.
Customize fade speed with the duration option inside transition:fade.
Always ensure elements actually enter or leave the DOM to see the fade effect.
Add ARIA attributes on controls toggling visibility for better accessibility.