Dark Mode: Class vs Media Strategy
Tailwind CSS offers two strategies to implement dark mode: the class-based strategy and the media query strategy. Each provides different ways to handle user preference or toggle dark mode in your app.
1. Configuration in tailwind.config.js
/** tailwind.config.js **/
// Class-based strategy
module.exports = {
darkMode: 'class', // or 'media'
content: ["./*.html"],
theme: {
extend: {},
},
plugins: [],
};
2. Class Strategy (`dark` class)
This strategy gives you full control to manually toggle dark mode using a parent class (`dark`), often on the `` or `
` element.
<html class="dark">
<div class="bg-white dark:bg-gray-900 text-black dark:text-white">
Dark mode enabled
</div>
</html>
Toggle the `dark` class with JavaScript to switch themes.
3. Media Strategy (`prefers-color-scheme`)
Tailwind automatically applies dark styles if the user's OS preference is dark mode.
module.exports = {
darkMode: 'media',
}
No need to toggle manually. Example:
<div class="bg-white dark:bg-gray-800 text-black dark:text-white">
Respects system dark mode preference
</div>
4. Class vs Media: When to Use?
Feature | Class | Media |
---|---|---|
Manual toggle | β | β |
Follows OS theme | β (unless you detect it) | β |
JavaScript control | β | β |
Better for SPAs | β | β |
5. Best Practices
- Use the
class
strategy if you want user-toggleable themes. - Use the
media
strategy for simplicity and OS integration. - Always test dark mode for readability and contrast accessibility.
Conclusion
Tailwindβs dark mode support is flexible and powerful. Choose the strategy that fits your projectβs needs, whether you want it to be automatic or user-controlled.