Ask any question about Tailwind CSS here... and get an instant response.
Post this Question & Answer:
How can I implement dark mode in Tailwind without duplicating styles?
Asked on Feb 03, 2026
Answer
Tailwind CSS provides a built-in dark mode feature that allows you to style your application without duplicating styles. You can enable dark mode in your Tailwind configuration and use the "dark" variant to apply styles conditionally.
<!-- BEGIN COPY / PASTE -->
<!-- Step 1: Enable dark mode in tailwind.config.js -->
module.exports = {
darkMode: 'class', // or 'media' for automatic based on user's system preference
// other configurations...
}
<!-- Step 2: Use the "dark" variant in your HTML -->
<div class="bg-white dark:bg-gray-800 text-black dark:text-white">
<p>This text changes color based on the theme.</p>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- To toggle dark mode, add or remove the "dark" class on the root element (e.g., or ).
- Use JavaScript to programmatically switch themes by adding/removing the "dark" class.
- The "media" strategy automatically applies dark mode based on the user's system settings.
- Dark mode styles are applied using the "dark" variant, keeping your code DRY (Don't Repeat Yourself).
Recommended Links:
