简体   繁体   中英

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

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 stack overflow :

Stackoverflow 首选项设置


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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM