Buttery Smooth Page Transitions with WordPress

Browser support warning
This is experimental technology and is not widely supported by browsers yet. For best results use Chrome 111+ or Chrome Canary.

View transitions make it easy to animate elements (images, headings, divs, containers) between pages with some simple CSS. Google recently put out an article showing example use of the View Transition API with a single page application. Let’s look at how to use this new tech on a traditional multi-page WordPress website.

Browser Support: Read First

The View Transitions API is still in development (releasing soon?!) but we can get early access to it by enabling a flag in Chrome. In my testing, it was best to use Chrome Canary, as I was having issues with the standard version of Chrome.

To enable the viewTransition API:

  • In Chrome go to the URL chrome://flags
  • Find the viewTransition API for navigations and enable it

Once you restart your browser you’ll be able to see use a test websites that are using the View Transition API.

Getting Started: Add view-transition meta tag

The first thing to add is the meta tag that tells the browser how to handle page navigations on your site. To add this I used a GeneratePress hook element in the wp_head with a priority of 1. You generally want any meta tags as high in the document as possible.

<meta name="view-transition" content="same-origin" />

That’s all you need to add to get a basic cross-fade transition on every page of your website.

Simple image transition

To transition the image from one page to the other, we need to give the image a CSS property called view-transition-name, the name can be any value you’d like. In our image example we’re going to call it vt-post-featured-image-{ $post_id } we’re appending the post ID to the end of these so that each image has a unique identifier.

function view_transition_featured_image_style($html, $post_id, $post_thumbnail_id, $size, $attr) {
    if (is_home() || is_single()) {
        if (is_string($attr)) {
            $attr = array();
        global $post;
        // Add your inline styles to the $attr array
        $attr['style'] = 'view-transition-name: vt-post-featured-image-' . $post_id . ';';
        // Generate the new HTML with the modified $attr array
        $html = wp_get_attachment_image($post_thumbnail_id, $size, false, $attr);
    return $html;
add_filter('post_thumbnail_html', 'view_transition_featured_image_style', 10, 5);

Another requirement of this API is to add contain: layout to any elements we plan on transitioning. So for our example, we’ll add this to the blog archive post image and the single page featured image.

.blog .post-image img,
.single .featured-image img {
    contain: layout;