"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > View transition theme animations

View transition theme animations

Published on 2024-11-04
Browse:466

View transition theme animations

Add cool effect when trnsitionning from light to dark mode using css and view transitions

copied from @jhey on twitter

[!NOTE]
This assumes you've already have your dark light mode setup with some sort of function to update your theme

  1. Add the css
  /* Angled */
  [data-style='angled']::view-transition-old(root) {
    animation: none;
    z-index: -1;
  }

  [data-style='angled']::view-transition-new(root) {
    animation: unclip 1s;
    clip-path: polygon(-100vmax 100%, 100% 100%, 100% -100vmax);
  }

  @keyframes unclip {
    0% {
      clip-path: polygon(100% 100%, 100% 100%, 100% 100%);
    }
  }

  1. ensure data-style="angled" attribute is set on the root element in SPA react we use a useEffect hook
  useEffect(() => {
    // set the data-style attribute
    document.documentElement.dataset.style = "angled";
  }, []);

in SSR it can be set directly in the html tag

  1. wrap your theme change function in a documnet.startViewTransition to start the view transition
  function transitionColors() {
    if (typeof window !== "undefined") {
      document.startViewTransition(() => {
        const newTheme = theme  === "light" ? "dark" : "light";
        document.documentElement.dataset.theme = newTheme;
        updateTheme(newTheme);
      });
    }
  }

more transition styles can be added by including the corresponding css file and adding the correct data-style attribute

      

react example

If you like this type of css tricks consider following jhey

Release Statement This article is reproduced at: https://dev.to/tigawanna/view-transition-theme-animations-8n1?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3