How to do CSS like transitions in Svelte?

Ashutosh Kukreti

Shorthand properties are the CSS properties, allowing us to set the values of multiple CSS properties.

The transition is also a shorthand CSS property that facilitates us to define the transition between two states of an element. Like fading/sliding an HTML element.

In Svelte, the transition is inbuilt. In this article, we learn about it in Svelte transitions.

The svelte/transition module contains the following animation: blur, fade, fly, slide, scale, draw and crossfade.

They are used with the, in, or out directives.  The in and out directives works when the HTML element is added or removed from the DOM.

In our previous article, we discuss Animation in Svelte. If you haven't gone through the article, please visit this link.

We'll start with adding a new route animations/transition. If you are new here, before proceeding further you need to visit this link. To create a route, we need to create a new file animations/transition.svelte.

Add the following content in the transition.svelte:

<script>
    import { fade } from "svelte/transition"

    let options = { duration: 1000 }
    let show = true;

</script>
<h1>Transition in Svelte.</h1>

<label>Click here to view transitions</label>
<input type="checkbox" on:click={() => show = !show} />


{#if show}
    <h1 transition:fade={options}>Fading Away.</h1>
{/if}

We import the fade transition and set the duration in options variable. Then we create a checkbox and bind it with the onclick and set the value true or false.

Similarly, we can add the other transitions like blur, draw, scale, slide etc.

<script>
    import { fade, blur, scale, slide } from "svelte/transition"

    let options = { duration: 1000 }
    let show = true;

</script>
<h1>Transition in Svelte.</h1>

<label>Click here to view transitions</label>
<input type="checkbox" on:click={() => show = !show} />


{#if show}
    <h1 transition:fade={options}>Fading Away.</h1>
    <h1 transition:blur={options}> Text to Blur </h1>
    <h1 transition:scale={options}> Text to Scale </h1>
    <h1 transition:slide={options}> Text to Slide </h1>
{/if}

See you in the next article.

Svelte3JavaScriptBeginners