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 and JavaScript?
Asked on May 09, 2026
Answer
To implement a dark mode toggle with Tailwind CSS, you can use a combination of Tailwind's dark mode utilities and JavaScript to switch themes dynamically. Tailwind provides a "dark" variant that can be applied conditionally.
<!-- BEGIN COPY / PASTE -->
<button id="theme-toggle" class="p-2 bg-gray-200 dark:bg-gray-800 text-black dark:text-white">
Toggle Dark Mode
</button>
<script>
const toggleButton = document.getElementById('theme-toggle');
const rootElement = document.documentElement;
toggleButton.addEventListener('click', () => {
if (rootElement.classList.contains('dark')) {
rootElement.classList.remove('dark');
localStorage.setItem('theme', 'light');
} else {
rootElement.classList.add('dark');
localStorage.setItem('theme', 'dark');
}
});
// Initialize theme based on localStorage
if (localStorage.getItem('theme') === 'dark') {
rootElement.classList.add('dark');
}
</script>
<!-- END COPY / PASTE -->Additional Comment:
- Tailwind's dark mode is typically configured in the `tailwind.config.js` file with the `darkMode` option set to 'class'.
- JavaScript is used here to toggle the 'dark' class on the `html` element, which applies dark mode styles.
- Local storage is utilized to persist the user's theme preference across sessions.
- Ensure your HTML elements use Tailwind's dark mode classes, such as `dark:bg-gray-800`, to reflect changes.
Recommended Links:
