Search code examples
javascriptvue.jstailwind-csstailwind-in-js

how to apply transition effects when switching from light mode to dark in tailwind 2.0?


So I'm building a small-ish project with tailwindCSS and thought of implementing the dark mode. I made a button and mapped it to put the dark class in the html tag. After testing for a bit, I realized that switching looked kind of odd because it is happening instantaneously. Is there a way to apply a transition duration or timing function to this change?

Here's the basic logic of how I'm handling the change (also I'm using vue):

<template>
  <!-- <span class="material-icons">&#xE51C;&#xE518;</span> -->
  <input @click="darkClassToggle" id="toggle" class="toggle" type="checkbox" />
</template>

<script>
export default {
  name: "darkModeToggle",
  methods: {
    darkClassToggle() {
      const toggle = document.querySelector(".toggle");
      const html = document.firstElementChild;
      if (toggle.checked) {
        html.classList.remove("dark");
      } else {
        html.classList.add("dark");
      }
    },
  },
};
</script>

Thank you for any help


Solution

  • Adding to the suggestion above, rather than append transition and duration-300 to every tag with a dark: variant, simply add it globally to your CSS files (I'm assuming that's index.css) and It will affect every element like so

    body * {
        @apply transition-colors duration-200;
    }
    

    This will target every descendant of body and apply those tailwind classes you want on them automatically.

    I hope this helps