Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 922
Reuben Rapose Avatar asked Dec 29 '25 00:12

Reuben Rapose


2 Answers

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!

like image 103
krishnaacharyaa Avatar answered Dec 30 '25 12:12

krishnaacharyaa


I tried the method of setting darkMode to class in the tailwind.config.js file as was suggested in another answer, but despite taking all the steps, this wasn't working for me.

In my case, all I needed to force dark mode in my app was to adjust the media queries in my main.css (AKA globals.css or whatever else you've called it).

/* main.css */

@tailwind base;
@tailwind components;
@tailwind utilities;

/* All your tailwind definitions with @apply rules are here */


/* If the user prefers dark mode, 
we of course apply color-scheme: dark, as usual */
@media (prefers-color-scheme: dark) {
  html {
    color-scheme: dark;
  }
}

/* If the user prefers light mode, 
we still enforce color-scheme: dark, despite the user preference */
@media (prefers-color-scheme: light) {
  html {
    color-scheme: dark;
  }
}

That's it. I didn't need to mess about in my tailwind.config.js or anywhere else.

like image 45
nonbeing Avatar answered Dec 30 '25 14:12

nonbeing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!