There's (yet another) new piece of CSS to learn! Hurrah!
Way back in 2011, jQuery mobile introduced the web to page-change animations. Clicking on a link would make your high-tech Nokia display a cool page-flip as you navigated from one page of a website to another. Just like an app!!!!
A decade-and-a-half later, and CSS has caught up (mostly). No more JavaScript, just spec-compliant CSS. Well, as long as you're using Chrome or Safari. Here's a quick quick MVP which will add some fancy animations as people browse your website.
Every page which wants animations has to "opt in". That means you need this:
CSS
@view-transition { navigation: auto; }
Next, you'll probably want to define some animations. Here are two I use:
CSS
@keyframes slide-in { from { translate: 100vw 0; } } @keyframes fade-out { to { opacity: 0; } }
Any standard CSS animation will work. Get creative!
Which elements do you want to animate? I'm just going to do the whole page.
CSS
html { view-transition-name: page; }
If you have a fancy app-like site, you might only want to animate specific parts of it.
While the page is transitioning, you can have something in the background to prevent things looking odd.
CSS
::view-transition { background: black; }
That's optional, but rather useful.
Next, we have to assign the animations to specific events. Here, I have the old page fade out and the new page slide in.
CSS
::view-transition-old(page) { animation-name: fade-out; animation-duration: 1s; } ::view-transition-new(page) { animation-name: slide-in; animation-duration: 1s; }
You can set the duration to whatever makes sense for your page and animation style.
Finally, and this is important, some people find animations painful or discombobulating. Make sure the animations are turned off for those who don't like them.
CSS
@media (prefers-reduced-motion: reduce) { ::view-transition-group(page) { animation-duration: 0s; } }
And that's it! A couple of dozen lines of CSS and you've got started with view transitions.
For more information, you can see the Chrome Devs' demo page, or take a read of the MDN documentation. There's also a full spec document if you like that sort of thing.
Right, I'm off to create some delightful animations!
One thought on “Getting started with simple CSS View Transitions”
Gui
One warning though. This doesn't play well with Safari’s back/forward previews. See https://github.com/w3c/csswg-drafts/issues/8333 and https://github.com/whatwg/html/issues/8782. I’m currently resorting to avoiding view transitions on mobile by wrapping them in
@media (pointer: fine)
but not sure that’s the best approach.More comments on Mastodon.