// tailwind.config.js module.exports = { darkMode: "class", // other configs here }
How to Write Tailwind CSS Dark Class Variant
To write the dark class variant you can prefix the class with "dark:" keyword and provide the property for it. For the example below the button will have a "blue" color on light theme and when the dark theme is enabled, the button color will be "gray".
<button class="bg-blue-500 hover:bg-blue-500 dark:bg-gray-400 dark:hover:bg-gray-500 ..."> <!-- ... --> </button>
Tailwind CSS Toggle Dark Mode
Do note that in order to enable the dark variant you will have to add the "dark" class in the "html" root element as follows. Adding and removing the class will toggle the modes.
<!-- Dark mode not enabled --> <html> <body> <!-- Will be white --> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body> </html> <!-- Dark mode enabled --> <html class="dark"> <body> <!-- Will be black --> <div class="bg-white dark:bg-black"> <!-- ... --> </div> </body> </html>
How to Toggle Tailwind CSS Mode With JavaScript
Generally, to toggle the modes you can use JavaScript and store the value in the "localStorage". The code itself is very straight forward and all you need is to check if any existing value is available from the "localStorage" which if it's available then you can set the "class" value to the page document.
// On page load or when changing themes, best to add inline in `head` to avoid FOUC if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) { document.documentElement.classList.add('dark') } else { document.documentElement.classList.remove('dark') } // Whenever the user explicitly chooses light mode localStorage.theme = 'light' // Whenever the user explicitly chooses dark mode localStorage.theme = 'dark' // Whenever the user explicitly chooses to respect the OS preference localStorage.removeItem('theme')
Leave a reply