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
1 Answer
Reset to default 7I 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
本文标签:
版权声明:本文标题:javascript - Tailwind CSS - Switch color theme between "light", "dark" or "system s 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741861430a2401646.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论