Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement a dark mode toggle with Tailwind CSS?
Asked on Feb 18, 2026
Answer
To implement a dark mode toggle with Tailwind CSS, you can use the "dark" variant to apply different styles based on a dark mode class. This involves toggling a class on the root element, typically the HTML or body tag, to switch between light and dark themes.
<!-- BEGIN COPY / PASTE -->
<div class="min-h-screen bg-white dark:bg-gray-900 text-black dark:text-white">
<button onclick="document.documentElement.classList.toggle('dark')">
Toggle Dark Mode
</button>
<p class="p-4">This text changes color based on the mode.</p>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- Use the "dark" variant in Tailwind to define styles for dark mode, such as "dark:bg-gray-900".
- The toggle function adds or removes the "dark" class on the root element, affecting all child elements with dark mode styles.
- Ensure that your Tailwind configuration includes the "darkMode" option set to "class".
- This example uses a simple JavaScript function to toggle the class, but you can also manage it with frameworks like React or Vue for more complex applications.
Recommended Links:
