The transition:fade directive in Svelte helps elements smoothly appear or disappear by fading in or out. It makes changes on the page look gentle and natural.
0
0
Transition directive (transition:fade) in Svelte
Introduction
When you want a message or alert to softly appear and then vanish.
When showing or hiding a menu or modal with a smooth fade effect.
When toggling content visibility to avoid sudden jumps on the screen.
When you want to improve user experience by adding simple animations.
When you want to highlight changes without distracting the user.
Syntax
Svelte
<element transition:fade />
Use
transition:fade on elements that enter or leave the DOM.You can customize the fade duration by passing options like
{ duration: 400 }.Examples
This paragraph will fade in when it appears and fade out when it disappears.
Svelte
<p transition:fade>Hello world!</p>
This div fades in and out over 1 second for a slower effect.
Svelte
<div transition:fade={{ duration: 1000 }}>Slow fade</div>The button fades in when
show is true and fades out when false.Svelte
{#if show}<button transition:fade>Click me</button>{/if}Sample Program
This Svelte component shows a button that toggles a message. The message uses transition:fade so it smoothly appears and disappears. The button has accessibility attributes for screen readers.
Svelte
<script> import { fade } from 'svelte/transition'; let visible = false; </script> <button on:click={() => visible = !visible} aria-pressed={visible} aria-label="Toggle message"> Toggle Message </button> {#if visible} <p transition:fade role="alert">Hello! This message fades in and out.</p> {/if}
OutputSuccess
Important Notes
The fade transition only works when elements are added or removed from the DOM.
You can combine transition:fade with other transitions or animations for more effects.
Always add accessible roles and labels when toggling content for better user experience.
Summary
transition:fade makes elements smoothly appear and disappear by fading.
Use it on elements that enter or leave the page to improve visual flow.
You can customize the fade speed with options like duration.