view-transition-name: The New Way to Make CSS Transitions Between Pages and Images
Content Index
Here we have another very interesting API that reminds me a lot of the Hero effect we have in Flutter, which, for example, we can apply to images. Personally, I think this is where it's most noticeable, but you can actually use it with any element.
We have an image in the list view, and when you click on it, you can see it performs a smooth scaling animation for the detail page. It's important to note that IT MUST BE THE SAME IMAGE. It's not abrupt, as is often the default in web applications, but much more fluid and natural.
The API: view-transition-name
For this, we use the view-transition API, specifically the view-transition-name property. This property defines a unique name that will be used to link the same element in different views, for example, from the list to the detail view.
In the list view (index), we assign the corresponding name:
<img class="post" *** src="image1.png" style="view-transition-name: {{ $b->slug }}">
In the detail view, we do exactly the same thing.
<img class="post" *** src="image1.png" style="view-transition-name: {{ $book->slug }}">
The above implementation is from a Laravel project, but you can replicate it in other technologies like Django and with other fields like id…
It's key that the name is identical in both views. If we change it even slightly, as in the example with a different value, the animation won't apply and the change will be abrupt again.
Restrictions on names
Keep in mind that you can't use spaces or special characters (such as periods, quotes, etc.). Therefore, it's not recommended to use a filename or path directly. Instead, it's best to use the slug or a clean variable, similar to how variables are named in JavaScript or CSS.
Applying the view-transition-name to other elements
Although we're using an image here, you can apply this animation to any HTML element. In other examples, it could be a <header>, a button, or any content block.
Compatibility and support
Browser support is quite good. If the browser doesn't support it, it simply ignores it—just like the @view-transition property above—and the behavior will be the default (no animation). No problem:
https://developer.mozilla.org/en-US/docs/Web/CSS/view-transition-name
The only thing I'm not entirely convinced about is that you have to define the view-transition-name directly in the HTML, which can make the markup a bit messy. Still, it's worth it for how easy it is to use and for the elegant visual effect we achieve.
In short: good, simple, compatible, and with great results.
I agree to receive announcements of interest about this Blog.
Page Effects with view-transition-name: Hero-style Magic CSS without JS in Flutter.