Welcome to my site—now in light or dark mode based on your system settings.
Dark mode isn’t just a trend—it’s expected by many users, especially on mobile and in low-light environments. In this guide, I’ll show you how to leverage system preferences and Tailwind’s built-in support to deliver a seamless dark mode experience on your Astro site.
tailwind.config.js
.darkMode
to 'media'
to follow the user’s OS preference:
// tailwind.config.js
module.exports = {
darkMode: 'media', // Options: 'media' or 'class'
content: ['./src/**/*.{astro,js,jsx,ts,tsx,mdx}'],
theme: { extend: {} },
plugins: [],
};
3. Rebuild your styles:
npm run build
⸻
Use Tailwind’s dark: prefix to define alternate styles:
Welcome to my site—now in light or dark mode based on your system settings.
⸻
If you prefer a toggle switch instead of—or in addition to—system control, switch to ‘class’ mode: 1. Change darkMode:
darkMode: ‘class’,
2. Add a toggle script in your layout:
3. Style the button and persist choice in localStorage if desired.
⸻
Benefits for Your Business • User Comfort: Respects system settings and reduces eye strain. • Performance: No extra JavaScript files or runtime CSS—styles are compiled at build time. • SEO & Accessibility: Improves user satisfaction and time on site, which can boost search rankings.
⸻
Takeaway
With just a few lines in tailwind.config.js and your templates, you can provide a fast, reliable dark mode that adapts automatically to your customers’ preferences—no maintenance required.
©Copyright 2020 by Avid Tech Usa. Built with ♥ by Omar Madjitov.