javascripthtmlcssuser-interfacetailwind-css

How to force dark-mode using TailwindCSS on browsers?


I have a website with proper implementation for dark/light UI using TailwindCSS.

I was wondering if there is a way to force the website to load in dark mode until the user specifically toggles light mode on by clicking the toggle button.

Why? Cause I prefer how the website looks in dark mode, but since the light/dark themeing is properly implemented I'd rather keep it and force it to load in dark mode despite user's browser settings.


Solution

  • Try the following

    In tailwind.config.js set the darkMode to class

    module.exports = {
      darkMode: 'class',
      // ...
    }
    

    And when you need the darkMode just add ClassName of dark inside the html tag

    <html className="dark">
    <body>
      <!-- Will be black -->
      <div className="bg-white dark:bg-black">
        <!-- ... -->
      </div>
    </body>
    </html>
    

    And when you need the light just remove ClassName of dark inside the html tag

    Hope it helps!