Home / Snippets / Tailwind CSS Dark Mode
Tailwind CSS Dark Mode cover

Tailwind CSS Dark Mode

1.4K

3 years ago

0 comments

Out of the box, Tailwind CSS can be configured to allow a dark mode variant. To enable this you can set the "darkMode" option in the tailwind.config.js file to have a "class" value.
// 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>
The dark variant will work with any other classes such as border, text, opacity, margin, paddings and etc.

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')

Other Reads

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this