Dark Mode Toggle Sun And Moon Switch
A settings card for a hiking journal app with a pill switch on the right: a yellow sun knob on a sky track in light mode, and a pale moon knob on a deep indigo track in dark mode. The knob slides across with a slight springy overshoot, and the whole block recolours. It starts from the device's light or dark setting and keeps following it until someone presses the switch.
Code
import { useEffect, useState } from "react";
// A sun and moon switch that flips the theme of the block around it. Starts from the device setting.
export default function DarkModeToggleSunAndMoonSwitch() {
const [dark, setDark] = useState(false);
useEffect(() => {
// Follow prefers-color-scheme until the visitor picks for themselves.
const mq = window.matchMedia("(prefers-color-scheme: dark)");
setDark(mq.matches);
const onChange = (e: MediaQueryListEvent) => setDark(e.matches);
mq.addEventListener("change", onChange);
return () => mq.removeEventListener("change", onChange);
}, []);
return (
<section className={`px-5 py-14 transition-colors duration-300 motion-reduce:transition-none ${dark ? "bg-slate-950" : "bg-slate-100"}`}>
<div className={`mx-auto max-w-md rounded-2xl border p-6 transition-colors duration-300 motion-reduce:transition-none ${dark ? "border-slate-800 bg-slate-900" : "border-slate-200 bg-white"}`}>
<div className="flex items-center justify-between gap-4">
<div>
<h2 className={`text-base font-semibold ${dark ? "text-white" : "text-slate-900"}`}>Appearance</h2>
<p id="dm1-desc" className={`text-sm ${dark ? "text-slate-400" : "text-slate-600"}`}>{dark ? "Dark theme is on" : "Light theme is on"}</p>
</div>
<button
type="button"
role="switch"
aria-checked={dark}
aria-label="Dark mode"
aria-describedby="dm1-desc"
onClick={() => setDark(!dark)}
className={`relative h-10 w-[76px] shrink-0 rounded-full p-1 transition-colors duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 motion-reduce:transition-none ${dark ? "bg-indigo-950 ring-offset-slate-900 focus-visible:ring-indigo-300" : "bg-sky-200 ring-offset-white focus-visible:ring-sky-600"}`}
>
<span className={`absolute inset-y-1 left-1 grid w-8 place-items-center rounded-full shadow transition-transform duration-300 ease-[cubic-bezier(.3,1.4,.5,1)] motion-reduce:transition-none ${dark ? "translate-x-9 bg-slate-200 text-indigo-950" : "translate-x-0 bg-amber-300 text-amber-700"}`}>
{dark ? (
<svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true" className="fill-current"><path d="M15.5 13.2A7 7 0 0 1 6.8 4.5 7 7 0 1 0 15.5 13.2z" /></svg>
) : (
<svg viewBox="0 0 20 20" width="18" height="18" aria-hidden="true" className="fill-current"><circle cx="10" cy="10" r="4" /><path d="M9 1h2v3H9zm0 15h2v3H9zM1 9h3v2H1zm15 0h3v2h-3zM3.3 4.7l1.4-1.4 2.1 2.1-1.4 1.4zm10 10 1.4-1.4 2.1 2.1-1.4 1.4zM3.3 15.3l2.1-2.1 1.4 1.4-2.1 2.1zm10-10 2.1-2.1 1.4 1.4-2.1 2.1z" /></svg>
)}
</span>
</button>
</div>
<div className={`mt-6 rounded-xl p-4 text-sm transition-colors duration-300 motion-reduce:transition-none ${dark ? "bg-slate-800 text-slate-300" : "bg-slate-50 text-slate-700"}`}>
<p className={`font-semibold ${dark ? "text-white" : "text-slate-900"}`}>Trailhead Journal</p>
<p className="mt-1">Your entries, maps and packing lists switch with the theme. Night reading is easier on the eyes in the tent.</p>
</div>
</div>
</section>
);
}
Install with one command: npx shadcn@latest add https://we.inc/r/dark-mode-toggle-sun-and-moon-switch.json
When to use it
- A site header or settings screen needs one obvious control for light and dark themes.
- Your design already has light and dark colour tokens and you need the switch that changes between them.
- Visitors arrive from both light and dark devices and the page should match them by default.
- You want a theme control that reads well at a glance because the icon shows the current theme.
How to customize it
- Edit the variables in the `.dm1` and `.dm1[data-theme="dark"]` rules to set both palettes; every surface reads from them.
- Move `data-theme` from the `.dm1` wrapper to the html element and change the selectors to `:root` to theme a whole site.
- Change the spring by editing `cubic-bezier(.3, 1.4, .5, 1)`; use `ease` for a plain slide.
- Add persistence inside `apply()` by saving the value with your own storage and reading it before the page paints.
Accessibility
- The control is a button with role switch and aria-checked, so screen readers announce Dark mode, on or off.
- The line under the heading states the current theme in words and is linked to the switch with aria-describedby.
- Both themes keep body text above 4.5 to 1 contrast, and the color-scheme property makes native controls match.
Questions
Does this toggle follow the system dark mode?
Yes. On load it reads matchMedia("(prefers-color-scheme: dark)") and listens for changes, so a page left open will switch when the device does. Once the visitor presses the switch, their choice wins until the page reloads.
How do I make the choice survive a reload?
In the apply function, write the chosen value to the storage your site uses. Then add a few lines in the head that read it and set data-theme on the html element before anything is drawn, so the saved theme appears without a flash.
Why a switch role instead of a checkbox?
A real checkbox works too. The button with role switch is used here because the knob artwork is easier to style on a button, and switch tells assistive technology that the change takes effect immediately rather than on submit.
Can I use this with Tailwind dark: classes?
Yes. Instead of changing data-theme on a wrapper, add or remove the dark class on the html element and set Tailwind's dark mode to the class or selector strategy. The switch markup stays the same.
Related: Dark Mode Toggle Switch in React and Tailwind with System Setting and Four Styles, CSS Toggle Switch Collection with 15 Styles on a Real Checkbox, Sizes, Disabled and RTL, Photoreal Dark Mode Toggle Switch: a Ceramic Rocker on a Sunlit Plaster Wall that Dims the Room to Lamplight.
More toggles and switches or all free UI components. Build your site free to have a full site built around it.
More in Toggles
- Dark Mode Toggle Switch in React and Tailwind with System Setting and Four Styles
- Enamel Lever Billing Switch in WebGL on Sunlit Terrazzo That Throws Over Centre Between Monthly and Yearly
- Guarded Toggle Switch Row with Red Flip-Up Safety Covers You Lift Before Each Switch Will Arm
- Hotel Keycard Door Lock Switch with a Card That Dips into the Reader, a Lamp That Turns Green and a Lever That Drops
- Lathe-Turned Metal Dial Switch with Detents and Light That Stays Put
- Louvred Window Shutters Toggle That Tilt Their Slats and Swing Open onto a Coastal Photograph
- Open-Gate Manual Gear Lever Selector with a Chrome H-Pattern Plate and a Ball Knob You Drag Through the Slots
- Photoreal Dark Mode Toggle Switch: a Ceramic Rocker on a Sunlit Plaster Wall that Dims the Room to Lamplight
Product
Who It's For
- For Agencies
- For Freelancers
- For Hosting Providers
- For SaaS Platforms
- For Startups
- For Financial Services
- For Healthcare
Features
Resources
- Blog
- Help Center
- Free Business Tools
- Free UI Components
- Website Templates
- Template Collections
- Website Examples
- Guides
- Comparisons
- Alternatives
- Best Lists
- Reviews
- Pricing Guides
- Use Cases
- Glossary & Guides
- Integrations
- Developers
- Benchmark
- Windows App