Posts Learn Components Snippets Categories Tags Tools About

Tailwind CSS Dark Mode

Learn how to enable tailwindcss dark mode option for your website

Created on Aug 24, 2021


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 ...">
  <!-- ... -->
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 -->
  <!-- Will be white -->
  <div class="bg-white dark:bg-black">
    <!-- ... -->

<!-- Dark mode enabled -->
<html class="dark">
  <!-- Will be black -->
  <div class="bg-white dark:bg-black">
    <!-- ... -->

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)) {
} else {

// 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

Other Reads

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

Load comments for Tailwind CSS Dark Mode