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 CSS? Pending Review
Asked on Jan 18, 2026
Answer
Implementing a dark mode toggle with Tailwind CSS involves using the "dark" variant to apply different styles based on a class on the root element. Here's a basic example of how you can achieve this.
<!-- 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-gray-200 dark:bg-gray-800 rounded">
Toggle Dark Mode
</button>
<p class="p-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 (in this case, a div with id "app").
- Tailwind's "dark:" variant is used to apply styles when the "dark" class is present.
- Ensure your Tailwind configuration allows dark mode by setting "darkMode" to 'class' in your tailwind.config.js.
- This example uses JavaScript to toggle the class, but you can also manage it with frameworks like React or Vue.
Recommended Links:
