Using CSS View-Transition API

January 1, 2025
~1 min read
CSSTransitionsWeb API

Overview

In this update I integrated the experimental CSS view-transition API to enable smoother page transitions.

Implementation Steps

  1. Added CSS rules for view transitions using the ::view-transition pseudo-element.
  2. Triggered transitions via document.startViewTransition() before DOM updates.
  3. Configured easing and timing for a smooth effect.

Example

tsx
1/* CSS */
2    @keyframes fade-in {
3      from {
4        opacity: 0;
5      }
6    }
7
8    @keyframes fade-out {
9      to {
10        opacity: 0;
11      }
12    }
13
14    @keyframes slide-from-right {
15      from {
16        transform: translateX(30px);
17      }
18    }
19
20    @keyframes slide-to-left {
21      to {
22        transform: translateX(-30px);
23      }
24    }
25
26    #main {
27      view-transition-name: main;
28    }
29
30    ::view-transition-old(main) {
31      animation: 90ms cubic-bezier(0.4, 0, 1, 1) both fade-out, 300ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
32    }
33
34    ::view-transition-new(main) {
35      animation: 210ms cubic-bezier(0, 0, 0.2, 1) 90ms both fade-in,
36        300ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
37    }
38
39    /* JavaScript */
40    const handleClick = (e: MouseEvent<HTMLAnchorElement>) => {
41        if (!document.startViewTransition) {
42          // browser does not support view transition. Continue the default behavior.
43          return;
44        } else {
45          // browser supports view transition. Animate the transition.
46          e.preventDefault();
47          document.startViewTransition(() => {
48            router.push(href as string);
49          });
50        }
51    };
Using CSS View-Transition API | My Blog