Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement dark mode toggle functionality using Tailwind CSS?
Asked on Dec 26, 2025
Answer
To implement a dark mode toggle with Tailwind CSS, you can use the "dark" variant to apply different styles based on a class on the root element. Here's a basic setup to demonstrate how you can toggle dark mode using Tailwind's dark mode utilities.
<!-- BEGIN COPY / PASTE -->
<div id="app" class="min-h-screen bg-white dark:bg-gray-900 text-black dark:text-white">
<button onclick="toggleDarkMode()" class="p-2 bg-gray-200 dark:bg-gray-800 rounded">
Toggle Dark Mode
</button>
<p class="mt-4">This is a sample text.</p>
</div>
<script>
function toggleDarkMode() {
document.getElementById('app').classList.toggle('dark');
}
</script>
<!-- END COPY / PASTE -->Additional Comment:
- The "dark" class is toggled on the root element to switch between light and dark mode.
- Tailwind's dark mode utilities (e.g., "dark:bg-gray-900") apply styles when the "dark" class is present.
- Ensure your Tailwind configuration is set to "class" mode for dark mode functionality.
- Consider persisting the dark mode state using local storage for a better user experience.
Recommended Links:
