Ask any question about Tailwind CSS here... and get an instant response.
How can I implement dark mode toggle with Tailwind CSS and JavaScript?
Asked on Dec 13, 2025
Answer
To implement a dark mode toggle using Tailwind CSS, you can utilize the `dark` variant in Tailwind combined with a simple JavaScript toggle to switch themes. This involves adding a class to the HTML element to enable dark mode styling.
<!-- 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">
<h1 class="text-xl">Hello, World!</h1>
<p>This is a simple dark mode toggle example.</p>
</div>
</body>
</html>
<!-- END COPY / PASTE -->Additional Comment:
- Tailwind's `dark` variant allows you to apply styles conditionally based on the presence of a `dark` class on the HTML element.
- Use JavaScript to toggle the `dark` class on the `document.documentElement` (the `` tag) to switch between light and dark modes.
- Ensure your Tailwind configuration file includes the `darkMode` option set to 'class' to enable this functionality.
- Consider storing the user's preference in local storage for persistence across sessions.
Recommended Links:
