How to Implement Dark Mode on Your Website: A Step-by-Step Guide
Dark mode is a user-friendly feature that reduces eye strain and saves battery life on OLED screens. By toggling between light and dark themes, you can significantly improve the browsing experience. In this guide, I’ll show you how to implement dark mode using CSS custom properties and a bit of JavaScript.
The core idea is to define color variables in CSS and switch their values by toggling a class or attribute on the <html> element. This approach keeps your code clean and maintainable. Let’s break it down into four key steps.
1. Define CSS Custom Properties
Start by declaring your color palette in the :root selector for the light theme. Then create a [data-theme="dark"] selector that overrides those same variables with dark colors. For example, set --bg-color to #ffffff in light mode and #121212 in dark mode. Use these variables throughout your stylesheets.
2. Add a Toggle Button
Insert a simple toggle button in your HTML (e.g., a <button id="theme-toggle">). In your JavaScript, listen for the click event and toggle the data-theme attribute on the <html> element between "light" and "dark". Use document.documentElement to access the root element.
3. Persist User Preference
To remember the user’s choice, store the theme in localStorage. In your script, check for a saved value on page load and apply it immediately. When the toggle is clicked, update both the attribute and the storage entry. This ensures the theme stays consistent across sessions.
4. Respect System Preferences
Enhance the experience by reading the user’s system preference via the prefers-color-scheme media query. Use window.matchMedia('(prefers-color-scheme: dark)') to detect the default theme. If no stored preference exists, start with the system setting. This makes your dark mode feel native and intuitive.
Implementing dark mode is straightforward with this variable-based approach. It’s lightweight, accessible, and gives users the control they expect. Test your implementation across different browsers and devices to ensure a smooth transition. Happy coding!