Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How do I implement dark mode toggle with Tailwind CSS?
Asked on Dec 22, 2025
Answer
To implement a dark mode toggle with Tailwind CSS, you can use the `dark` variant to apply styles conditionally based on a dark mode class. This approach typically involves toggling a class on the root element (like `html` or `body`) to switch between light and dark themes.
<!-- BEGIN COPY / PASTE -->
<html lang="en">
<body class="bg-white text-black dark:bg-gray-900 dark:text-white">
<button onclick="document.documentElement.classList.toggle('dark')">
Toggle Dark Mode
</button>
<div class="p-4">
<h1 class="text-2xl">Hello, World!</h1>
<p>This is a paragraph.</p>
</div>
</body>
</html>
<!-- END COPY / PASTE -->Additional Comment:
- Tailwind's `dark` variant allows you to define styles that apply when a `dark` class is present on a parent element.
- In the example, clicking the button toggles the `dark` class on the `` element, switching the theme.
- Ensure your Tailwind configuration includes the `darkMode` option set to `'class'` to enable this feature.
- This approach is simple and leverages Tailwind's built-in utilities without additional JavaScript libraries.
Recommended Links:
