Ask any question about Tailwind CSS here... and get an instant response.
How do I implement dark mode toggle with Tailwind?
Asked on Dec 01, 2025
Answer
To implement a dark mode toggle in Tailwind CSS, you can use the "dark" variant to apply different styles based on a dark mode class on the root element. Here's a simple example of how you can set up a dark mode toggle using Tailwind's built-in utilities.
<!-- BEGIN COPY / PASTE -->
<div id="app" class="bg-white dark:bg-gray-800 text-black dark:text-white min-h-screen flex items-center justify-center">
<button onclick="toggleDarkMode()" class="px-4 py-2 bg-blue-500 text-white rounded">
Toggle Dark Mode
</button>
</div>
<script>
function toggleDarkMode() {
document.getElementById('app').classList.toggle('dark');
}
</script>
<!-- END COPY / PASTE -->Additional Comment:
- The "dark" variant in Tailwind allows you to define styles that apply when a parent element has the "dark" class.
- In this example, the "dark" class is toggled on the root div element to switch between light and dark modes.
- Ensure your Tailwind configuration includes the "darkMode" option set to "class" to enable this functionality.
- This approach uses JavaScript to toggle the class, but you can also manage it through frameworks or libraries for state management.
Recommended Links:
