How to Create Dark Mode in Tailwind CSS

How to Create Dark Mode in Tailwind CSS

Dark mode has become an essential feature in modern web development, offering users a more comfortable viewing experience in low-light environments while also reducing eye strain and battery consumption on mobile devices. Implementing dark mode with Tailwind CSS is straightforward and highly customizable. This guide will walk you through the process step by step.

Understanding Tailwind’s Dark Mode Support

Tailwind CSS includes built-in support for dark mode through its dark: variant prefix. This allows you to apply different styles when dark mode is active without writing separate CSS or using JavaScript.

Setting Up Dark Mode

To get started with dark mode in Tailwind, you’ll first need to configure how it should be activated. Open your tailwind.config.js file and add the darkMode setting:

// tailwind.config.js
module.exports = {
  darkMode: 'class', // or 'media' for system preference
  theme: {
    // ...
  }
}

You have two options:

  1. Class strategy ('class'): Toggles dark mode when a specific class (typically dark) is applied to an HTML element, usually the <html> tag. This gives users control to toggle regardless of their system preferences.
  2. Media strategy ('media'): Automatically follows the user’s system preferences using the prefers-color-scheme media query.

The class strategy offers more flexibility, as noted in Tailwind’s official documentation.

Implementing a Dark Mode Toggle

If you’ve chosen the class strategy, you’ll need a way to toggle dark mode. Here’s a simple implementation using JavaScript:

// Add this to your main JavaScript file
const darkModeToggle = document.getElementById('dark-mode-toggle');
darkModeToggle.addEventListener('click', () => {
  document.documentElement.classList.toggle('dark');
  
  // Optional: Save preference to localStorage
  if (document.documentElement.classList.contains('dark')) {
    localStorage.setItem('darkMode', 'enabled');
  } else {
    localStorage.setItem('darkMode', 'disabled');
  }
});

// Check for saved preference when page loads
if (localStorage.getItem('darkMode') === 'enabled') {
  document.documentElement.classList.add('dark');
}

Styling for Dark Mode

Once your configuration is set up, you can use the dark: prefix with any Tailwind utility class to apply styles specifically for dark mode:

<div class="bg-white text-black dark:bg-gray-800 dark:text-white">
  This text will be black on white in light mode, and white on dark gray in dark mode.
</div>

Common Dark Mode Color Combinations

According to CSS-Tricks, these color combinations work well for dark mode:

  • Light mode: bg-white with text-gray-900
  • Dark mode: dark:bg-gray-900 with dark:text-gray-100

For UI elements like buttons and cards:

  • Light mode: bg-gray-100
  • Dark mode: dark:bg-gray-800

Creating a Comprehensive Dark Theme

For a well-designed dark mode, consider styling these common elements:

Text

<p class="text-gray-800 dark:text-gray-200">
  This paragraph adapts to dark mode.
</p>

Cards and Containers

<div class="bg-white shadow-md rounded-lg p-6 dark:bg-gray-800 dark:shadow-none">
  Card content here
</div>

Buttons

<button class="bg-blue-500 hover:bg-blue-600 text-white dark:bg-blue-600 dark:hover:bg-blue-700">
  Click me
</button>

Form Elements

<input type="text" class="border border-gray-300 bg-white dark:border-gray-700 dark:bg-gray-900 dark:text-white">

Advanced Techniques

Custom Color Palette

As recommended by Flowbite, you can define custom colors specifically for dark mode in your Tailwind configuration:

// tailwind.config.js
module.exports = {
  darkMode: 'class',
  theme: {
    extend: {
      colors: {
        primary: {
          DEFAULT: '#1e40af',
          dark: '#3b82f6' // Brighter blue for dark mode
        }
      }
    }
  }
}

Then use them in your HTML:

<button class="bg-primary text-white dark:bg-primary-dark">
  Primary Button
</button>

Images and Media

For images that need different versions in dark mode, you can use the dark: variant with the hidden and block utilities:

<img src="/light-logo.png" class="block dark:hidden">
<img src="/dark-logo.png" class="hidden dark:block">

Testing Dark Mode

To properly test your dark mode implementation:

  1. Test with both system dark mode and your toggle mechanism
  2. Check all UI components and states
  3. Ensure text remains readable with sufficient contrast
  4. Verify that images and media adapt properly

Performance Considerations

As web.dev points out, switching to dark mode shouldn’t negatively impact performance. Tailwind’s approach is efficient since it’s all handled through CSS classes.

Conclusion

Implementing dark mode with Tailwind CSS is a relatively simple process that greatly enhances user experience. By leveraging Tailwind’s dark mode variant, you can create a seamless transition between light and dark themes while maintaining a consistent design language.

Remember to test your implementation across different devices and browsers to ensure a smooth experience for all users. With these techniques, you’ll be able to provide a polished dark mode option that your users will appreciate.

What is the purpose of the styled-jsx library in Next.js

What is the purpose of the getStaticPaths function in dynamic routes

Explain the concept of SSR (Server-Side Rendering) vs. CSR (Client-Side Rendering) in React

How can you implement lazy loading in a Next.js application

How does data fetching work in Next.js

What are hooks, and how are they used in Next.js

How can you optimize images in a Next.js application

What is the purpose of the getInitialProps function in Next.js

How can you deploy a Next.js application