Skip to main content
Back to Blog
Tailwind CSSDark ModeReact

Tailwind CSS Dark Mode Guide: CSS Variables and Theme Switching

6 min read

Implement seamless dark mode in React and Next.js apps with Tailwind CSS — using CSS variables, the class strategy, next-themes integration, and system preference detection.

Implementing a smooth, accessible dark mode is one of the most requested features in modern web applications, and Tailwind CSS with Next.js makes it remarkably straightforward when you follow the right patterns. Muhammad Sufyan of Sufyan Frontend — who built the dark UI throughout his portfolio at https://sufyan-frontend.vercel.app — shares the complete implementation guide for 2026.

Choosing Your Dark Mode Strategy

Tailwind CSS supports two dark mode strategies — media and class. The media strategy automatically applies dark styles based on the user's system preference. The class strategy applies dark styles when a dark class is present on the HTML element, giving you programmatic control over the current theme. For any application with a manual theme toggle, the class strategy is the right choice.

CSS Variables for Smooth Theming

The most maintainable approach to dark mode in Tailwind is driving your theme through CSS custom properties rather than duplicating every colour utility. Define your semantic colour variables for light and dark themes, then reference them throughout your Tailwind config:

/* globals.css */
:root {
  --background: #ffffff;
  --foreground: #0f172a;
  --card: #f8fafc;
  --primary: #0ea5e9;
}

.dark {
  --background: #0f172a;
  --foreground: #f1f5f9;
  --card: #1e293b;
  --primary: #38bdf8;
}

next-themes Integration

The next-themes library is the easiest way to add theme switching to a Next.js app. It handles system preference detection, localStorage persistence, hydration mismatch prevention, and the class toggling on the HTML element.

  • Install next-themes and wrap your app with ThemeProvider
  • Use useTheme() hook to read and set the current theme in components
  • Set attribute="class" to match Tailwind's class strategy
  • Use suppressHydrationWarning on the HTML element to prevent flicker

Conclusion

Dark mode done well requires the right architectural decisions from the start — class strategy, CSS variables, and next-themes for hydration safety. Muhammad Sufyan's portfolio at https://sufyan-frontend.vercel.app demonstrates these patterns in a real production Next.js application. Explore the implementation and adapt the patterns for your own projects.