Dark Mode Support in TailwindCSS
? Dark Mode Support in Tailwind CSS
Tailwind CSS provides built-in utilities to easily support dark mode in your projects, making it simple to switch styles between light and dark themes.
How Tailwind Dark Mode Works
Tailwind supports two main strategies:
| Mode | Description |
|---|---|
media | Uses the user's OS preference (prefers-color-scheme CSS media query) |
class | You toggle dark mode manually by adding a .dark class on a parent element (usually <html> or <body>) |
1. Enable Dark Mode in tailwind.config.js
By default, Tailwind dark mode is disabled.
Example config:
module.exports = { darkMode: 'class', // or 'media' theme: { extend: {}, }, plugins: [],}2. Usage with class Strategy
Add .dark class to the root element
<html class="dark"> <body> <div class="bg-white dark:bg-gray-900 text-black dark:text-white"> Hello Dark Mode! </div> </body></html>Toggle dark mode dynamically with JavaScript
const html = document.documentElement;html.classList.toggle('dark'); // Switches dark mode on/off3. Usage with media Strategy
No need to add .dark class manually. Tailwind will apply dark styles automatically if user prefers dark mode in OS settings.
<div class="bg-white dark:bg-gray-900 text-black dark:text-white"> This respects OS dark mode preference</div>4. Dark Mode Utility Syntax
Use the dark: prefix to apply styles only in dark mode.
<button class="bg-gray-200 dark:bg-gray-800 text-gray-900 dark:text-gray-100 p-4 rounded"> Dark Mode Button</button>5. Example: Dark Mode Card
<div class="p-6 max-w-sm mx-auto bg-white dark:bg-gray-800 rounded-xl shadow-md text-center"> <h2 class="text-gray-900 dark:text-gray-100 font-bold text-xl mb-2">Dark Mode Card</h2> <p class="text-gray-700 dark:text-gray-300">This card adapts to light and dark themes.</p></div>6. Tips
Use semantic colors that work in both modes (
gray-900vsgray-100).Test your dark mode colors for accessibility and contrast.
Combine with JavaScript to toggle dark mode with a button.
Would you like me to help create a dark mode toggle button with Tailwind?