Posts Learn Components Snippets Categories Tags About
/

Tailwind CSS Dark Mode

Learn how to enable tailwindcss dark mode option for your website

Created on Aug 24, 2021

21 views

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

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Tailwind CSS Dark Mode

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More