TailwindCSS - Switch color theme between "Light", "Dark" OR "System setting"

Viewed 2331

TailwindCSS provides 2 different ways to enable darkmode on your website.


First through media, meaning if your operating system supports darkmode and has it activated your website will automatically be displayed in darkmode (if you defined it).

tailwind.config.js

module.exports = {
    darkMode: 'media',
};

Second through class, meaning if your < html > tag has the class="dark" aassigned your website will also be displayed in darkmode (if you defined it).

tailwind.config.js

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

Is there a simple way of using both of these options at once?

The effect i want to achieve is that the user can set their preference between Lightmode, Darkmode and System Settings

similar to the function used here on stackoverflow:

Stackoverflow preference settings


If this option is not possible direct with TailwindCSS, what would be the cleanest and simplest workaround?


Information about my project:

  • TailwindCSS
  • Laravel 8
  • Fortify
  • Jetstream
  • Livewire

Thanks Leon

1 Answers

I had the exact same use case in my project. I solved it by using the class mode together with a media watcher. You need to set the class on page load and on a change of the settings and also when the event fires.

const setTheme = (isDark) => {
  document.documentElement.classList.remove('dark');
  if (isDark) {
    document.documentElement.classList.add('dark');
  }
};

if (settingIsAuto) {
  setTheme(window.matchMedia('(prefers-color-scheme: dark)').matches);
}

window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
  const newIsDark = e.matches;
  if (settingIsAuto) {
    setTheme(newIsDark);
  }
});

// watch for settings changes
Related