Ask any question about Tailwind CSS here... and get an instant response.
How can I implement dark mode toggle functionality with Tailwind CSS?
Asked on Dec 12, 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. This typically involves toggling a class on the root element to switch between light and dark modes.
<!-- BEGIN COPY / PASTE -->
<div id="app" class="bg-white dark:bg-gray-900 text-black dark:text-white min-h-screen">
<button onclick="toggleDarkMode()" class="p-2 bg-blue-500 text-white">
Toggle Dark Mode
</button>
<p class="p-4">This is a paragraph that changes with dark mode.</p>
</div>
<script>
function toggleDarkMode() {
document.getElementById('app').classList.toggle('dark');
}
</script>
<!-- END COPY / PASTE -->Additional Comment:
- Tailwind's "dark" variant allows you to apply styles conditionally based on a "dark" class.
- In the example, the button toggles the "dark" class on the root element, switching styles.
- Ensure your Tailwind configuration file has "darkMode" set to "class" to use this method.
- Consider using local storage to remember the user's preference across sessions.
Recommended Links:
