Page Transitions with the View Transition API: Part 1
A native way to animate between states has long been on the wish list for many webs developers. Now with the currently experimental View Transition API theres a way to do this. I have added page transitions to this blog and while I had some frustrations I am hopeful about the possible uses for the API.
Setup
Since it is still experimental (at time of writing) you can only view this in Chrome by enabling it chrome://flags#view-transition-on-navigation
and adding this to the head of your website <meta name="view-transition" content="same-origin" />
.
The default animation is a simple cross-fade between two elements, just add a view-transition-name
with the same value to the two elements e.g. .article { view-transition-name: --article }
. In this example every blog article page has an article.article
element so when a user navigates between those page the transition is animated. Note that I have used a prefix of two dashes for the view transition name to mirror CSS custom properties but this is a not a requirement.
Then the fun part, you can customize the transitions using keyframe animations and view transition pseudo elements. This example fades out the old article while sliding to the left and the new article fades in while sliding from the right.
.article { view-transition-name: --article }
@keyframes fade-in {
from { opacity: 0; }
}
@keyframes fade-out {
to { opacity: 0; }
}
@keyframes slide-from-right {
from { translate: 32px; }
}
@keyframes slide-to-left {
to { translate: -32px; }
}
::view-transition-group(--article) {
animation-fill-mode: both;
animation-timing-function: ease-out;
animation-duration: .15s, .3s;
}
::view-transition-old(--article) {
animation-name: fade-out, slide-to-left;
}
::view-transition-new(--article) {
animation-name: fade-in, slide-from-right;
}
Challenges
We have added some nice page transition animations but adding additional animations brought up some new challenges, in part 2 I will dicuss some of the solutions and wordkarounds I have used.
References
- Smooth and simple transitions with the View Transitions API by Jake Archibald
- Getting started with View Transitions on multi-page apps by Dave Rupert
- View transitions and stacking context by Nic Chan
- The View Transitions API And Delightful UI Animations (Part 2) by Adrian Bece