Skip to content
Tailwind CSS

Dark Mode

Toggle themes with the dark: variant and class strategy.

By EZ4Code Team
dark-modetheming

Code

<!-- Class-based dark mode (default uses prefers-color-scheme) -->
<div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100">
  Adapts to theme
</div>

<button class="bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700">
  Toggle me
</button>

<!-- Enable class strategy in config -->
<!--
// tailwind.config.js
module.exports = {
  darkMode: "class",
  // ...
};
-->

<!-- Toggling in JS -->
<!--
document.documentElement.classList.toggle("dark");
-->

Explanation

The dark: variant applies utilities in dark mode, controlled either by the OS prefers-color-scheme or a .dark class on the html element. Setting darkMode to class in config switches to manual control so a toggle button can flip themes. Every utility can be prefixed with dark: to restyle per theme.

More Tailwind CSS Snippets