Dark mode is a popular feature that enhances usability in low-light environments and offers users a sleek, aesthetic alternative. With Tailwind CSS and a small amount of vanilla JavaScript, you can provide a seamless toggle between light and dark themes.
Why Add Dark Mode?
- Reduces eye strain in low-light settings
- Aligns with user system preferences
- Adds a modern, polished look to your site
Setup Tailwind for Dark Mode
Enable dark mode in your tailwind.config.js
:
module.exports = {
darkMode: 'class', // or 'media' for system preference
content: ['./src/**/*.{html,js,jsx}'],
theme: {
extend: {},
},
plugins: [],
};
Toggle Implementation with JavaScript
Add a dark mode toggle button to your HTML:
<button id="dark-toggle" class="p-2 rounded focus:outline-none focus:ring">
π
</button>
Then use this script to enable theme switching:
const toggle = document.getElementById('dark-toggle');
const html = document.documentElement;
toggle.addEventListener('click', () => {
html.classList.toggle('dark');
localStorage.theme = html.classList.contains('dark') ? 'dark' : 'light';
});
// Apply saved preference on load
if (localStorage.theme === 'dark' ||
(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
html.classList.add('dark');
} else {
html.classList.remove('dark');
}
Example Dark Mode Styles
Use Tailwind's dark:
variants to style elements:
<section class="bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 p-6">
<h1 class="text-3xl font-bold mb-4">Hello, Dark Mode!</h1>
<p class="mb-4">This section adapts automatically when dark mode is toggled.</p>
<a href="#" class="text-indigo-600 dark:text-indigo-400 font-semibold">
Learn more
</a>
</section>
-
bg-white dark:bg-gray-900
changes background per theme -
text-gray-900 dark:text-gray-100
ensures legible text - Links adopt dual-tone styling via
text-indigo-600 dark:text-indigo-400
Accessibility & UX Considerations
- Ensure sufficient contrast in both themes (check WCAG)
- Persist user preference in
localStorage
- Avoid flashing by applying preference early (e.g., inline script in
<head>
) - Provide clear toggle labels and icons
Summary
Enabling dark mode with Tailwind and JavaScript is straightforward and impactful. By using dark:
variants and managing preferences, you offer users customized experiences with minimal effort and consistent design.
If you'd like a comprehensive guide to design patterns, theming strategies, and Tailwind architecture at scale, check out:
Mastering Tailwind at Scale: Architecture, Patterns & Performance
Elevate your siteβs experience β implement dark mode with elegance and performance using Tailwind CSS.
Top comments (0)