Back to roadmaps tailwind Course

Dark Mode Configuration

Dark mode has become a standard requirement for modern web applications. Tailwind CSS includes a built-in dark: variant, allowing you to style your site differently when dark mode is active.


1. Choosing a Dark Mode Strategy

Tailwind supports two strategies to determine when dark mode is enabled:

A. Media Strategy (Default)

Uses the visitor system preferences (prefers-color-scheme). If their operating system is set to dark mode, the dark styles apply automatically.

B. Class Strategy

Allows you to toggle dark mode manually using a button. It looks for a dark class on the root HTML tag:

<!-- Dark mode active -->
<html className="dark">
  <body>...</body>
</html>

To enable the class strategy, update your tailwind.config.js configuration file:

// tailwind.config.js
module.exports = {
  darkMode: "class", // Enables manual class toggling instead of system media
  content: ["./src/**/*.{html,js,ts,jsx,tsx,astro}"],
  theme: {
    extend: {},
  },
}

2. Using the dark: Variant

Once configured, prefix any style class with dark: to apply it only when dark mode is active:

<div className="bg-white text-gray-900 dark:bg-gray-950 dark:text-gray-50 p-6 border dark:border-gray-800 rounded">
  <h3>System Configuration</h3>
  <p className="text-gray-500 dark:text-gray-400">Settings and metrics dashboard.</p>
</div>

Transitioning Color Shifts

To prevent colors from shifting instantly when toggling themes, add a transition helper to the root container:

<div className="transition-colors duration-300">...</div>

3. Implementing a Toggle Script

If you choose the class strategy, use a simple JavaScript toggle function to add or remove the dark class from the document root element:

// Function to toggle dark mode status
function toggleDarkMode() {
  const root = document.documentElement;
  
  if (root.classList.contains("dark")) {
    root.classList.remove("dark");
    localStorage.setItem("theme", "light");
  } else {
    root.classList.add("dark");
    localStorage.setItem("theme", "dark");
  }
}
Published on Last updated: