Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement dark mode toggling using Tailwind CSS?
Asked on Feb 21, 2026
Answer
To implement dark mode toggling in Tailwind CSS, you can use the "dark" variant, which allows you to define styles that apply when dark mode is enabled. Tailwind provides a built-in dark mode feature that can be toggled using a class on the root element.
<!-- BEGIN COPY / PASTE -->
<html lang="en">
<head>
<script>
// Toggle dark mode
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">
Toggle Dark Mode
</button>
<div class="p-4">
<p class="text-lg">This is a paragraph.</p>
</div>
</body>
</html>
<!-- END COPY / PASTE -->Additional Comment:
- Tailwind's dark mode is configured in the `tailwind.config.js` file, typically using the `media` or `class` strategy.
- The `class` strategy allows toggling dark mode by adding or removing the `dark` class on the root element.
- Ensure your HTML elements have both default and dark mode styles using the `dark:` prefix.
- Use JavaScript to toggle the `dark` class on the `` or `` element to switch modes.
Recommended Links:
