乐闻世界logo
搜索文章和话题

How to implement dark mode in TailwindCSS?

2026年2月17日 14:36

TailwindCSS's dark mode feature allows developers to easily implement dark themes, supporting both automatic detection of system preferences and manual switching.

Dark Mode Configuration

1. Enable Dark Mode

Configure dark mode strategy in tailwind.config.js.

javascript
// tailwind.config.js module.exports = { // Use class strategy (manual switching) darkMode: 'class', // Or use media strategy (automatic system preference detection) darkMode: 'media', // Or support both methods darkMode: ['class', 'media'], }

2. Strategy Selection

class strategy:

  • Requires manually adding dark class to HTML elements
  • Supports user manual theme switching
  • More flexible, suitable for applications requiring theme switching

media strategy:

  • Automatically detects system color preferences
  • No manual switching needed
  • Suitable for applications not requiring theme switching

Using Dark Mode

1. Basic Usage

html
<!-- Use dark: prefix --> <div class="bg-white dark:bg-gray-800 text-gray-900 dark:text-white"> Dark mode supported content </div> <!-- Button example --> <button class=" bg-blue-500 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700 text-white "> Button </button> <!-- Card example --> <div class=" bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 "> <h3 class="text-gray-900 dark:text-white font-bold mb-2"> Card title </h3> <p class="text-gray-600 dark:text-gray-300"> Card content </p> </div>

2. Complete Page Example

html
<!DOCTYPE html> <html class="dark"> <head> <title>Dark Mode Example</title> </head> <body class="bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-white"> <!-- Navigation --> <nav class=" bg-white dark:bg-gray-800 shadow-md px-6 py-4 "> <div class="max-w-7xl mx-auto flex justify-between items-center"> <h1 class="text-xl font-bold">Logo</h1> <button id="theme-toggle"> Toggle Theme </button> </div> </nav> <!-- Main content --> <main class="max-w-7xl mx-auto px-6 py-8"> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <!-- Card --> <div class=" bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 "> <h3 class="text-gray-900 dark:text-white font-bold mb-2"> Card title </h3> <p class="text-gray-600 dark:text-gray-300"> Card content </p> </div> </div> </main> </body> </html>

Implementing Theme Switching

1. JavaScript Implementation

javascript
// Theme switching function function toggleTheme() { const html = document.documentElement; if (html.classList.contains('dark')) { html.classList.remove('dark'); localStorage.setItem('theme', 'light'); } else { html.classList.add('dark'); localStorage.setItem('theme', 'dark'); } } // Initialize theme function initTheme() { const savedTheme = localStorage.getItem('theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; if (savedTheme === 'dark' || (!savedTheme && prefersDark)) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } } // Listen for system theme changes window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => { if (!localStorage.getItem('theme')) { if (e.matches) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } } }); // Initialize initTheme();

2. React Implementation

jsx
import { useState, useEffect } from 'react'; function ThemeToggle() { const [isDark, setIsDark] = useState(false); useEffect(() => { // Initialize theme const savedTheme = localStorage.getItem('theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; if (savedTheme === 'dark' || (!savedTheme && prefersDark)) { setIsDark(true); document.documentElement.classList.add('dark'); } }, []); const toggleTheme = () => { setIsDark(!isDark); if (!isDark) { document.documentElement.classList.add('dark'); localStorage.setItem('theme', 'dark'); } else { document.documentElement.classList.remove('dark'); localStorage.setItem('theme', 'light'); } }; return ( <button onClick={toggleTheme} className=" px-4 py-2 rounded bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-300 dark:hover:bg-gray-600 " > {isDark ? '☀️ Light Mode' : '🌙 Dark Mode'} </button> ); }

3. Vue Implementation

vue
<template> <button @click="toggleTheme" class=" px-4 py-2 rounded bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white hover:bg-gray-300 dark:hover:bg-gray-600 " > {{ isDark ? '☀️ Light Mode' : '🌙 Dark Mode' }} </button> </template> <script> export default { data() { return { isDark: false, }; }, mounted() { this.initTheme(); }, methods: { initTheme() { const savedTheme = localStorage.getItem('theme'); const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; if (savedTheme === 'dark' || (!savedTheme && prefersDark)) { this.isDark = true; document.documentElement.classList.add('dark'); } }, toggleTheme() { this.isDark = !this.isDark; if (this.isDark) { document.documentElement.classList.add('dark'); localStorage.setItem('theme', 'dark'); } else { document.documentElement.classList.remove('dark'); localStorage.setItem('theme', 'light'); } }, }, }; </script>

Dark Mode Best Practices

1. Color Design

javascript
// tailwind.config.js module.exports = { theme: { extend: { colors: { // Define dark mode specific colors gray: { 50: '#f9fafb', 100: '#f3f4f6', 200: '#e5e7eb', 300: '#d1d5db', 400: '#9ca3af', 500: '#6b7280', 600: '#4b5563', 700: '#374151', 800: '#1f2937', 900: '#111827', 950: '#030712', }, }, }, }, }

2. Semantic Colors

html
<!-- Use semantic colors --> <div class=" bg-background dark:bg-background-dark text-primary dark:text-primary-dark border-border dark:border-border-dark "> Semantic colors </div>
javascript
// tailwind.config.js module.exports = { theme: { extend: { colors: { background: '#ffffff', 'background-dark': '#1f2937', primary: '#3b82f6', 'primary-dark': '#60a5fa', border: '#e5e7eb', 'border-dark': '#374151', }, }, }, }

3. Gradients and Shadows

html
<!-- Dark mode gradients --> <div class=" bg-gradient-to-r from-blue-500 to-purple-500 dark:from-blue-600 dark:to-purple-600 "> Gradient background </div> <!-- Dark mode shadows --> <div class=" shadow-md dark:shadow-xl dark:shadow-gray-900 "> Dark mode shadow </div>

Advanced Usage

1. Image Adaptation

html
<!-- Display different images based on theme --> <picture> <source srcset="dark-image.png" media="(prefers-color-scheme: dark)"> <img src="light-image.png" alt="Adaptive image"> </picture> <!-- Use CSS variables --> <img src="light-image.png" class="dark:hidden" alt="Light mode image" > <img src="dark-image.png" class="hidden dark:block" alt="Dark mode image" >

2. SVG Icons

html
<!-- Use CSS variables to control SVG color --> <svg class="w-6 h-6 text-gray-600 dark:text-gray-300" fill="currentColor"> <path d="..."/> </svg>

3. Animation Transitions

html
<!-- Add smooth transitions --> <div class=" bg-white dark:bg-gray-800 text-gray-900 dark:text-white transition-colors duration-300 "> Smooth transition </div>

Common Issues

1. Flash Issue

Theme flashing may occur on page load, can be solved by:

html
<!-- Add inline script in head --> <script> if (localStorage.getItem('theme') === 'dark' || (!localStorage.getItem('theme') && window.matchMedia('(prefers-color-scheme: dark)').matches)) { document.documentElement.classList.add('dark'); } </script>

2. Third-party Library Compatibility

Some third-party libraries may not support dark mode, need manual adaptation:

css
/* Add dark mode support for third-party libraries */ .dark .third-party-component { background-color: #1f2937; color: #f9fafb; }

3. Performance Optimization

Avoid using too many shadows and gradients in dark mode to improve performance.

Considerations

  1. Accessibility: Ensure contrast in dark mode meets WCAG standards
  2. User Preferences: Respect user's system preference settings
  3. Persistence: Use localStorage to save user's theme choice
  4. Smooth Transitions: Add transition effects for color changes
  5. Test Coverage: Test dark mode on different devices and browsers

Summary

TailwindCSS's dark mode feature provides:

  • Simple and easy-to-use API
  • Flexible configuration options
  • Good development experience
  • Comprehensive browser support

By properly using dark mode, you can provide users with better visual experience while enhancing the application's modern feel and professionalism.

标签:Tailwind CSS