Smooth theme transitions
2 min read

When you have multiple elements with transitions on your website, toggling themes can be ugly. The more elements with transitions, the worse it looks especially if you have differing durations.

Try it out

A div that transitions at 300ms
A div that transitions at 700ms

Yuck

Wrap theme toggle logic with this snippet for smooth transitions

function toggleTheme(dark: boolean) {
  const css = document.createElement('style');
  css.type = 'text/css';
  css.appendChild(
    document.createTextNode(
      `* {
         -webkit-transition: none !important;
         -moz-transition: none !important;
         -o-transition: none !important;
         -ms-transition: none !important;
         transition: none !important;
      }`
    )
  );

  //toggle your theme here, using whatever method you prefer
  document.documentElement.classList.toggle("dark", dark);
  //
  
  const _ = window.getComputedStyle(css).opacity;
  document.head.removeChild(css);
}

Result

A div that transitions at 300ms
A div that transitions at 700ms

Credits to Paco Coursey

I actually discovered this technique while digging through the source code for Next Themes