3

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

  • 4
    On any element you want a transition to happen on just add the classes `transition` (or any other transition class) and `duration-300` (or your preferred speed) it will apply for theme changes as well since all that is changing usually with dark mode is colors. If however you have other things transitioning as well you'll need to enable them in your tailwind config file. – JHeth Jul 16 '21 at 01:51
  • Thank you! I figured it out and got it working. I was applying transition to html tag instead of body where I had declared the dark theme. – 76 69 6E 61 79 Jul 16 '21 at 08:11

2 Answers2

7

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

Jeffreyon
  • 86
  • 1
  • 4
1

Just add transition-colors duration-1000 classes to body like this:

<body class="transition-colors duration-1000">
  ...
</body>
AnasSafi
  • 5,353
  • 1
  • 35
  • 38