Dark mode helps reduce eye strain in low light. Using a class to switch modes lets you control when dark mode is on.
0
0
Class-based dark mode strategy in Tailwind
Introduction
You want users to toggle between light and dark mode manually.
You want to apply dark mode only to parts of your website.
You want to avoid relying on the user's system settings for dark mode.
You want to test dark mode easily during development.
You want consistent dark mode styling across your site.
Syntax
Tailwind
<!-- Add 'dark' class to a parent element --> <div class="dark"> <p class="bg-white dark:bg-gray-800 text-black dark:text-white">Hello, dark mode!</p> </div>
The
dark class on a parent triggers dark styles inside it.Use
dark: prefix in Tailwind to style elements for dark mode.Examples
The button background and text color change when the
dark class is present on the parent.Tailwind
<div class="dark"> <button class="bg-gray-200 dark:bg-gray-700 text-black dark:text-white">Click me</button> </div>
Applying
dark class on body switches the whole page to dark mode styles.Tailwind
<body class="dark"> <h1 class="text-gray-900 dark:text-gray-100">Welcome</h1> </body>
If no
dark class is present, dark styles won't apply.Tailwind
<div>
<p class="bg-white dark:bg-gray-800">Light background by default, dark background if parent has <code>dark</code> class.</p>
</div>Sample Program
This example uses Tailwind's class-based dark mode. Clicking the button toggles the dark class on the html element. The box background and text colors change accordingly.
Tailwind
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Class-based Dark Mode Example</title> <script src="https://cdn.tailwindcss.com"></script> <script> tailwind.config = { darkMode: 'class' } </script> </head> <body class="p-6"> <button id="toggleDark" class="mb-4 px-4 py-2 bg-gray-300 dark:bg-gray-700 text-black dark:text-white rounded"> Toggle Dark Mode </button> <div id="container" class="p-6 bg-white dark:bg-gray-900 text-black dark:text-white rounded"> <h1 class="text-2xl font-bold mb-2">Hello, World!</h1> <p>This box changes colors when dark mode is toggled.</p> </div> <script> const button = document.getElementById('toggleDark'); button.addEventListener('click', () => { document.documentElement.classList.toggle('dark'); }); </script> </body> </html>
OutputSuccess
Important Notes
Make sure to set darkMode: 'class' in your Tailwind config to use this strategy.
Toggle the dark class on a parent element like html or body to switch modes.
Use semantic HTML and ensure good color contrast for accessibility in both modes.
Summary
Class-based dark mode uses a dark class on a parent to control dark styles.
Tailwind's dark: prefix applies styles only when the dark class is present.
This method lets users toggle dark mode manually and gives you full control over styling.