Creating a Dark Mode Toggle

Dark mode reduces eye strain in low-light environments and is becoming increasingly expected by many users on the modern web. The cleanest way to implement a dark mode toggle is a combination of CSS custom properties for theming and a few lines of JavaScript to switch between them.

Step 1: Define Your Themes with CSS Variables

CSS custom properties (variables) are the foundation of a good dark mode toggle. You define your color palette once on the :root selector, and then every element in your stylesheet reads from these variables instead of using hardcoded colors. To switch themes, you only need to override the variable values on the body element. Every element automatically updates with them.

Here's an example:

Step 2: Toggle the Class with JavaScript

A simple toggle button (or checkbox switch) runs a single line of JavaScript to add or remove the dark-mode class on the <body>. When the class is present, the dark variable overrides take effect. When it's removed, the light defaults return:

Step 3: Remember the User's Preference with localStorage

Without persistence, the user's dark mode choice resets every time they reload the page. localStorage allows you to save the user's preference in their browser so that it's automatically restored on their next visit:

Full Working Example

Below is a complete working demonstration. Click the toggle switch in the header to switch between light and dark mode. Because the example runs in an isolated frame, the localStorage persistence is also demonstrable. Toggle it on, reload the preview, and it will remember your choice:

View Output Full Screen Preview