Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement dark mode toggle with Tailwind CSS?
Asked on Jan 25, 2026
Answer
Implementing a dark mode toggle in Tailwind CSS involves using the "dark" variant to apply different styles based on a dark mode class on the root element. You can toggle this class using JavaScript to switch between light and dark modes.
<!-- BEGIN COPY / PASTE -->
<div id="app" class="bg-white dark:bg-gray-800 text-black dark:text-white min-h-screen">
<button onclick="toggleDarkMode()" class="p-2 bg-gray-200 dark:bg-gray-700 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.
- Ensure your Tailwind configuration includes the "darkMode" option set to 'class' to enable this functionality.
- JavaScript is used to toggle the "dark" class on the root element, which changes the styles of all elements using dark mode variants.
- Consider storing the user's preference in local storage to persist the mode across sessions.
Recommended Links:
