admin管理员组

文章数量:1308569

Tailwind CSS provides two different ways to enable dark mode on your website.

The first way is through media, which means if your OS supports dark mode and it's activated. Your website will be automatically displayed in dark mode.

My tailwind.config.js:

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

The second way is through "class", meaning if your <html> tag has the class="dark" assigned. Your website will be displayed in dark mode.

My 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 "light", "dark" and "system settings".

Similar to the function that is used here on Stack Overflow:

If this option is not currently possible with Tailwind CSS, what would be the cleanest and simplest workaround?

Information about my project:

  • Tailwind CSS
  • Laravel 8
  • Fortify
  • Jetstream
  • Livewire

Tailwind CSS provides two different ways to enable dark mode on your website.

The first way is through media, which means if your OS supports dark mode and it's activated. Your website will be automatically displayed in dark mode.

My tailwind.config.js:

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

The second way is through "class", meaning if your <html> tag has the class="dark" assigned. Your website will be displayed in dark mode.

My 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 "light", "dark" and "system settings".

Similar to the function that is used here on Stack Overflow:

If this option is not currently possible with Tailwind CSS, what would be the cleanest and simplest workaround?

Information about my project:

  • Tailwind CSS
  • Laravel 8
  • Fortify
  • Jetstream
  • Livewire
Share Improve this question edited Feb 4, 2023 at 20:35 Ghost 5,0597 gold badges24 silver badges48 bronze badges asked Mar 5, 2021 at 19:55 leonnicklasleonnicklas 4631 gold badge6 silver badges23 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

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

本文标签: