Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement dark mode toggle using Tailwind CSS classes?
Asked on Feb 28, 2026
Answer
To implement a dark mode toggle with Tailwind CSS, you can use the "dark" variant to apply styles conditionally based on a class added to the HTML element. This requires a small JavaScript snippet to toggle the class.
<!-- BEGIN COPY / PASTE -->
<html lang="en">
<head>
<script>
function toggleDarkMode() {
document.documentElement.classList.toggle('dark');
}
</script>
</head>
<body class="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>
<div class="p-4">
<p class="text-lg">This text changes color based on the mode.</p>
</div>
</body>
</html>
<!-- END COPY / PASTE -->Additional Comment:
- Tailwind's "dark" variant allows you to define styles for dark mode using the "dark:" prefix.
- Ensure your Tailwind configuration is set up to enable dark mode, typically by setting "darkMode: 'class'" in your tailwind.config.js file.
- The JavaScript function toggles the "dark" class on the HTML element, switching styles based on the presence of this class.
- This example uses a button to toggle dark mode, but you can integrate this functionality into any UI element or event.
Recommended Links:
