Reuben Rapose
Reuben Rapose

Reputation: 217

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.

Upvotes: 16

Views: 20766

Answers (3)

krishnaacharyaa
krishnaacharyaa

Reputation: 25010

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!

Upvotes: 17

Hedg
Hedg

Reputation: 1

This worked for me, hope it will for you.

Here is the thing to consider:

savedTheme=localStorage.getItem('theme');

if (!savedTheme) {
  document.documentElement.classList.add('dark')
};

onMounted(()=>{
  const savedTheme=localStorage.getItem('theme');

  if (!savedTheme||savedTheme==='dark') { 
    document.documentElement.classList.add('dark');
  } else { 
    document.documentElement.classList.remove('dark');
  }
});

Upvotes: -1

nonbeing
nonbeing

Reputation: 7327

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.

Upvotes: 15

Related Questions