Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement dark mode toggle functionality with Tailwind CSS?
Asked on Jan 06, 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. Here's a basic example of how to set up a dark mode toggle.
<!-- 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 is a sample text.</p>
</div>
</body>
</html>
<!-- END COPY / PASTE -->Additional Comment:
- The `dark` class is toggled on the `` or `` element to switch themes.
- Tailwind's `dark` variant allows you to define styles for dark mode by prefixing classes with `dark:`.
- Ensure your Tailwind configuration includes the `darkMode` option set to `'class'` to use this method.
- JavaScript is used here to toggle the class, but you can also manage this with frameworks like React or Vue.
Recommended Links:
