Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement a dark mode toggle using Tailwind's dark variant?
Asked on Apr 28, 2026
Answer
To implement a dark mode toggle using Tailwind's dark variant, you can leverage Tailwind's built-in support for dark mode by applying the "dark" class conditionally based on user interaction.
<!-- BEGIN COPY / PASTE -->
<div class="min-h-screen bg-white dark:bg-gray-900 text-black dark:text-white">
<button onclick="document.documentElement.classList.toggle('dark')" class="p-2 bg-gray-200 dark:bg-gray-800 rounded">
Toggle Dark Mode
</button>
<p class="mt-4">This text changes color based on the mode.</p>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- Tailwind's dark mode is configured by default to use the "class" strategy, which means you toggle the "dark" class on the root element.
- Ensure your Tailwind configuration file is set to use "darkMode: 'class'" if you want to use the class strategy.
- The example uses JavaScript to toggle the "dark" class on the document's root element.
- All elements with dark mode styles should use the "dark:" prefix to apply styles conditionally.
Recommended Links:
