Introduction
Dark mode isn’t just a design trend anymore — it’s a must-have feature for any modern web app. With Tailwind CSS and a pinch of JavaScript, you can implement a smooth, persistent dark mode in just a few lines of code.
Let’s dive in and give your website that sleek, night-friendly vibe 🌙
Prerequisites
Before we begin, make sure you have:
• A project set up with Tailwind CSS
• Basic understanding of HTML and JavaScript
• A browser and text editor (VS Code recommended)
Step 1: Enable Dark Mode in Tailwind Config
Tailwind makes it incredibly easy to enable dark mode.
Open your tailwind.config.js and add this line:
This tells Tailwind to apply dark styles whenever a .dark class is present on your or
tag.Step 2: Add Light & Dark Styles in Your HTML
Now, create two versions of your background and text colors using Tailwind’s dark mode classes.
dark: prefix automatically applies the dark version of each style when .dark is active on the body.
Step 3: Add JavaScript for Toggle Functionality
We’ll use a simple script to toggle the dark class and store the user’s preference in localStorage so it persists after reload.
That’s all it takes. The button now toggles dark mode — and your site remembers the user’s choice.
Step 4: Smooth Transitions for a Premium Feel
Add this to your body class or global CSS for a smooth color fade effect when toggling themes:
.transition-colors {
transition: background-color 0.3s, color 0.3s;
}
Tailwind already includes utilities like transition-colors and duration-300, so you can easily control the timing.
Step 5: Optional — Sync with System Preferences
Want your site to automatically detect the user’s OS theme?
You can use the prefers-color-scheme media query:
if (
localStorage.getItem('theme') === 'dark' ||
(!localStorage.getItem('theme') &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
body.classList.add('dark');
}
This ensures your dark mode is smart and adapts instantly to user preferences.
Final Touch
With just a few lines of code, you’ve implemented a fully functional, persistent, and smooth dark mode powered by Tailwind CSS and JavaScript.
Your users will love the elegant transition and modern look — and your codebase stays clean, thanks to Tailwind’s class-based styling.



Top comments (0)