Dark Mode Toggle Switches in CSS and React

Updated 2026-10-28. 4 toggles.

A dark mode toggle is a switch that flips a theme attribute or class on the page root, which swaps a set of CSS colour variables. Start from the visitor's prefers-color-scheme setting, let the toggle override it, and remember the choice. Each toggle below works with the keyboard and announces its state.

A two-state switch is the simplest choice and fits most marketing sites: one tap and the page changes. If your audience includes people who switch their whole device between light and dark at sunset, use the three-way light, dark and system picker, because a plain switch forgets that the system setting exists.

In tight headers the morphing icon button takes the least room while still showing which theme is on. The preview toggle suits settings pages, where seeing a small copy of the page change helps people decide before they leave the screen.

All of these drive the same thing underneath: a data-theme attribute on a wrapper, with colours defined as CSS variables for each value. In Tailwind, set darkMode to selector (or class in older versions) and the toggle's attribute or class switches every dark: utility at once.

Compare them

VariantBuilt withSize (gzipped)Running costBrowser support
Dark Mode Toggle Sun And Moon SwitchCSS and a small script1.8 KBA transform on the knob and colour transitions on three surfaces, plus one media query listener.All current browsers
Dark Mode Toggle Light Dark System SegmentedCSS and a small script1.2 KBThree radio inputs, one change listener and one media query listener; no animation at all.All current browsers
Dark Mode Toggle Morphing Sun To Moon Icon ButtonCSS only1.3 KBThree SVG parts moved by transform transitions inside one 24px icon; idle cost is zero.All current browsers
Dark Mode Toggle With Live Page PreviewCSS and a small script1.6 KBA checkbox, one change listener and short colour transitions on a few preview blocks.All current browsers

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.

<!-- Put data-theme on the html element in a real site; here it sits on a wrapper so the demo is self-contained. -->
<div class="dm1" data-theme="light">
  <div class="dm1-card">
    <div class="dm1-head">
      <div>
        <h2 class="dm1-title">Appearance</h2>
        <p class="dm1-desc" id="dm1-desc">Light theme is on</p>
      </div>
      <button type="button" class="dm1-switch" role="switch" aria-checked="false" aria-label="Dark mode" aria-describedby="dm1-desc">
        <span class="dm1-knob">
          <svg class="dm1-sun" viewBox="0 0 20 20" aria-hidden="true"><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>
          <svg class="dm1-moon" viewBox="0 0 20 20" aria-hidden="true"><path d="M15.5 13.2A7 7 0 0 1 6.8 4.5 7 7 0 1 0 15.5 13.2z"/></svg>
        </span>
      </button>
    </div>
    <div class="dm1-box">
      <p class="dm1-strong">Trailhead Journal</p>
      <p>Your entries, maps and packing lists switch with the theme.</p>
    </div>
  </div>
</div>

<style>
  /* Every colour is a variable; the dark theme only redefines the variables. */
  .dm1 { --bg: #f1f5f9; --card: #fff; --line: #e2e8f0; --ink: #0f172a; --muted: #475569; --box: #f8fafc; --track: #bae6fd; color-scheme: light; }
  .dm1[data-theme="dark"] { --bg: #020617; --card: #0f172a; --line: #1e293b; --ink: #fff; --muted: #94a3b8; --box: #1e293b; --track: #1e1b4b; color-scheme: dark; }

  .dm1 { background: var(--bg); padding: 56px 20px; font-family: ui-sans-serif, system-ui, sans-serif; transition: background-color .3s; }
  .dm1-card { max-width: 28rem; margin: 0 auto; padding: 24px; border: 1px solid var(--line); border-radius: 16px; background: var(--card); transition: background-color .3s, border-color .3s; }
  .dm1-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
  .dm1-title { margin: 0; font-size: 16px; color: var(--ink); }
  .dm1-desc { margin: 2px 0 0; font-size: 14px; color: var(--muted); }
  .dm1-box { margin-top: 24px; padding: 16px; border-radius: 12px; background: var(--box); color: var(--muted); font-size: 14px; }
  .dm1-box p { margin: 4px 0 0; }
  .dm1-strong { font-weight: 600; color: var(--ink); }

  /* The switch: a track with a round knob that slides 36px to the right when checked. */
  .dm1-switch { position: relative; flex-shrink: 0; width: 76px; height: 40px; padding: 0; border: 0; border-radius: 999px; background: var(--track); cursor: pointer; transition: background-color .3s; }
  .dm1-switch:focus-visible { outline: 2px solid #0284c7; outline-offset: 3px; }
  .dm1-knob { position: absolute; top: 4px; left: 4px; display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: #fcd34d; color: #b45309; box-shadow: 0 1px 3px rgb(0 0 0 / .25); transition: transform .3s cubic-bezier(.3, 1.4, .5, 1), background-color .3s; }
  .dm1-knob svg { width: 18px; height: 18px; fill: currentColor; }
  .dm1-moon { display: none; }
  .dm1-switch[aria-checked="true"] .dm1-knob { transform: translateX(36px); background: #e2e8f0; color: #1e1b4b; }
  .dm1-switch[aria-checked="true"] .dm1-sun { display: none; }
  .dm1-switch[aria-checked="true"] .dm1-moon { display: block; }

  @media (prefers-reduced-motion: reduce) {
    .dm1, .dm1-card, .dm1-switch, .dm1-knob { transition: none; }
  }
</style>

<script>
  (function () {
    var root = document.querySelector(".dm1");
    if (!root) return;
    var sw = root.querySelector(".dm1-switch"), desc = root.querySelector(".dm1-desc");
    var mq = window.matchMedia("(prefers-color-scheme: dark)");
    var chosen = false; /* becomes true once the visitor clicks */

    function apply(dark) {
      root.setAttribute("data-theme", dark ? "dark" : "light");
      sw.setAttribute("aria-checked", dark ? "true" : "false");
      desc.textContent = dark ? "Dark theme is on" : "Light theme is on";
      /* To remember the choice, save "dark" or "light" here with your own storage. */
    }
    apply(mq.matches);
    mq.addEventListener("change", function (e) { if (!chosen) apply(e.matches); });
    sw.addEventListener("click", function () {
      chosen = true;
      apply(sw.getAttribute("aria-checked") !== "true");
    });
  })();
</script>

With reduced motion: The knob jumps straight to its new side and the colours change without fading.

Running cost: A transform on the knob and colour transitions on three surfaces, plus one media query listener.

  • 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.

Full page for Dark Mode Toggle Sun And Moon Switch

Dark Mode Toggle Light Dark System Segmented

A warm stone settings card with a three-part track: Light, Dark and System. It is built on real radio buttons, so arrow keys move the choice. System is selected at first and the line above the track says which theme the device is using right now. Choosing Light or Dark fixes the theme regardless of the device.

<div class="dm2" data-theme="light">
  <!-- Real radio inputs: arrow keys move between options for free. -->
  <fieldset class="dm2-card">
    <legend class="dm2-title">Theme</legend>
    <p class="dm2-note">Following your device.</p>
    <div class="dm2-track">
      <label><input type="radio" name="dm2-theme" value="light"><span>Light</span></label>
      <label><input type="radio" name="dm2-theme" value="dark"><span>Dark</span></label>
      <label><input type="radio" name="dm2-theme" value="system" checked><span>System</span></label>
    </div>
  </fieldset>
</div>

<style>
  .dm2 { --bg: #f5f5f4; --card: #fff; --line: #e7e5e4; --ink: #1c1917; --muted: #57534e; --track: #f5f5f4; --chip: #fff; color-scheme: light; }
  .dm2[data-theme="dark"] { --bg: #1c1917; --card: #292524; --line: #44403c; --ink: #fafaf9; --muted: #d6d3d1; --track: #1c1917; --chip: #44403c; color-scheme: dark; }

  .dm2 { background: var(--bg); padding: 56px 20px; font-family: ui-sans-serif, system-ui, sans-serif; }
  .dm2-card { max-width: 28rem; margin: 0 auto; padding: 24px; border: 1px solid var(--line); border-radius: 16px; background: var(--card); }
  .dm2-title { float: left; width: 100%; padding: 0; font-size: 16px; font-weight: 600; color: var(--ink); }
  .dm2-note { clear: both; margin: 0; padding-top: 4px; font-size: 14px; color: var(--muted); }
  .dm2-track { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; margin-top: 20px; padding: 4px; border-radius: 12px; background: var(--track); }

  /* Hide the radio circle but keep it focusable; style the span next to it. */
  .dm2-track input { position: absolute; opacity: 0; width: 1px; height: 1px; }
  .dm2-track span { display: flex; align-items: center; justify-content: center; min-height: 44px; border-radius: 8px; font-size: 14px; font-weight: 500; color: var(--muted); cursor: pointer; }
  .dm2-track input:checked + span { background: var(--chip); color: var(--ink); box-shadow: 0 1px 2px rgb(0 0 0 / .15); }
  .dm2-track input:focus-visible + span { outline: 2px solid #f97316; outline-offset: 1px; }
</style>

<script>
  (function () {
    var root = document.querySelector(".dm2");
    if (!root) return;
    var note = root.querySelector(".dm2-note");
    var mq = window.matchMedia("(prefers-color-scheme: dark)");

    function update() {
      var mode = root.querySelector("input:checked").value;
      var dark = mode === "dark" || (mode === "system" && mq.matches);
      root.setAttribute("data-theme", dark ? "dark" : "light");
      note.textContent = mode === "system"
        ? "Following your device, which is " + (mq.matches ? "dark" : "light") + " right now."
        : "Always " + mode + ", whatever your device says.";
      /* Save `mode` (not the resolved theme) with your own storage to remember it. */
    }
    root.addEventListener("change", update);
    mq.addEventListener("change", update);
    update();
  })();
</script>

With reduced motion: Nothing here animates; the chosen option and page colours change in one step.

Running cost: Three radio inputs, one change listener and one media query listener; no animation at all.

  • Save the chosen mode rather than the resolved theme, so System keeps following the device after a reload.
  • Change the focus outline colour `#f97316` and both palettes in the two variable blocks at the top.

Dark Mode Toggle Morphing Sun To Moon Icon Button

A pottery studio header with a single round icon button at the end of the nav. In light mode it shows a sun with eight rays; pressing it spins the rays away, swells the disc and slides a mask circle across to bite out a crescent moon. The page behind recolours from peach to charcoal. It takes no more room than any other header icon.

<div class="dm3-page" data-theme="dark">
  <header class="dm3-bar">
    <a href="#" class="dm3-logo">Kiln and Co.</a>
    <button type="button" class="dm3-btn" aria-pressed="true" aria-label="Dark theme">
      <svg class="dm3" viewBox="0 0 24 24" aria-hidden="true">
        <!-- The mask: white shows, black hides. The black circle slides over the disc to cut a crescent. -->
        <mask id="dm3v-mask">
          <rect width="24" height="24" fill="white"/>
          <circle class="dm3-bite" cx="16" cy="8" r="6" fill="black"/>
        </mask>
        <circle class="dm3-core" cx="12" cy="12" r="5" fill="currentColor" mask="url(#dm3v-mask)"/>
        <path class="dm3-rays" d="M12 1.5v2M12 20.5v2M1.5 12h2M20.5 12h2M4.6 4.6l1.4 1.4M18 18l1.4 1.4M4.6 19.4 6 18M18 6l1.4-1.4" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
      </svg>
    </button>
  </header>
</div>

<style>
  .dm3-page { --bg: #fff7ed; --bar: #fff; --line: #fed7aa; --ink: #1c1917; --icon: #ea580c; padding: 48px 20px; background: var(--bg); transition: background-color .5s; font-family: ui-sans-serif, system-ui, sans-serif; }
  .dm3-page[data-theme="dark"] { --bg: #171717; --bar: #262626; --line: #404040; --ink: #ffedd5; --icon: #fed7aa; }
  .dm3-bar { display: flex; align-items: center; justify-content: space-between; max-width: 48rem; margin: 0 auto; padding: 10px 16px 10px 20px; border: 1px solid var(--line); border-radius: 16px; background: var(--bar); }
  .dm3-logo { font: 600 18px ui-serif, Georgia, serif; color: var(--ink); text-decoration: none; }
  .dm3-btn { display: grid; place-items: center; width: 44px; height: 44px; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--icon); cursor: pointer; }
  .dm3-btn:focus-visible { outline: 2px solid #f97316; outline-offset: 2px; }
  .dm3 { width: 24px; height: 24px; }

  /* Each part transforms around its own centre with a slight overshoot. */
  .dm3 * { transform-box: fill-box; transform-origin: center; transition: transform .5s cubic-bezier(.5, 1.25, .75, 1.25); }
  .dm3-bite { transform: translate(12px, -12px); }      /* sun: bite circle parked outside */
  .dm3-btn[aria-pressed="true"] .dm3-bite { transform: none; }               /* moon: bite moves in */
  .dm3-btn[aria-pressed="true"] .dm3-core { transform: scale(1.6); }         /* disc grows */
  .dm3-btn[aria-pressed="true"] .dm3-rays { transform: rotate(-30deg) scale(0); } /* rays spin away */

  @media (prefers-reduced-motion: reduce) { .dm3 *, .dm3-page { transition: none; } }
</style>

<script>
  (function () {
    var page = document.querySelector(".dm3-page");
    if (!page) return;
    var btn = page.querySelector(".dm3-btn");
    btn.addEventListener("click", function () {
      var dark = btn.getAttribute("aria-pressed") !== "true";
      btn.setAttribute("aria-pressed", dark ? "true" : "false");
      page.setAttribute("data-theme", dark ? "dark" : "light");
    });
  })();
</script>

With reduced motion: The icon swaps between sun and moon instantly with no rays spinning or disc growing.

Running cost: Three SVG parts moved by transform transitions inside one 24px icon; idle cost is zero.

  • Tune the overshoot in `cubic-bezier(.5, 1.25, .75, 1.25)` or the `.5s` duration.
  • Move the bite circle's `cx` and `cy` to change which side the crescent opens toward.

Dark Mode Toggle With Live Page Preview

A reader settings panel for a news site: a Dark reading mode switch on the left and a small browser window on the right showing a wireframe of an article page. Flipping the switch repaints the wireframe between white and deep navy, including its cards and its accent button. It is a native checkbox with role switch, so Space toggles it.

<div class="dm4">
  <div class="dm4-copy">
    <h2 class="dm4-title">Reader theme</h2>
    <p class="dm4-lead">Choose how the Northwind Ledger articles look on this device.</p>
    <!-- A native checkbox with role="switch": Space toggles it, and it is announced as on or off. -->
    <label class="dm4-row">
      <span>Dark reading mode</span>
      <input type="checkbox" role="switch" class="dm4-input" checked>
      <span class="dm4-track" aria-hidden="true"></span>
    </label>
  </div>
  <!-- Decorative mini page: it repaints from the same variables the real page would use. -->
  <div class="dm4-preview" data-theme="dark" aria-hidden="true">
    <div class="dm4-bar"><i></i><i></i><i></i></div>
    <div class="dm4-page">
      <b class="dm4-h"></b><b class="dm4-l"></b><b class="dm4-l dm4-short"></b>
      <div class="dm4-cards"><b></b><b></b><b></b></div>
      <b class="dm4-btn"></b>
    </div>
  </div>
</div>

<style>
  .dm4 { display: grid; gap: 32px; align-items: center; max-width: 48rem; margin: 0 auto; padding: 28px; border: 1px solid #e2e8f0; border-radius: 16px; background: #fff; font-family: ui-sans-serif, system-ui, sans-serif; }
  @media (min-width: 640px) { .dm4 { grid-template-columns: 1fr 1fr; } }
  .dm4-title { margin: 0; font-size: 18px; color: #0f172a; }
  .dm4-lead { margin: 4px 0 24px; font-size: 14px; color: #475569; }
  .dm4-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; min-height: 44px; padding: 8px 16px; border: 1px solid #e2e8f0; border-radius: 12px; font-size: 14px; font-weight: 500; color: #1e293b; cursor: pointer; }

  /* Switch: the real checkbox is invisible; the track after it draws the switch. */
  .dm4-input { position: absolute; opacity: 0; width: 1px; height: 1px; }
  .dm4-track { position: relative; flex-shrink: 0; width: 48px; height: 28px; border-radius: 999px; background: #cbd5e1; transition: background-color .2s; }
  .dm4-track::after { content: ""; position: absolute; top: 4px; left: 4px; width: 20px; height: 20px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgb(0 0 0 / .3); transition: transform .2s; }
  .dm4-input:checked + .dm4-track { background: #0284c7; }
  .dm4-input:checked + .dm4-track::after { transform: translateX(20px); }
  .dm4-input:focus-visible + .dm4-track { outline: 2px solid #0284c7; outline-offset: 2px; }

  /* Preview palettes */
  .dm4-preview { --p-page: #fff; --p-bar: #f8fafc; --p-line: #e2e8f0; --p-head: #1e293b; --p-card: #f1f5f9; --p-accent: #0284c7; overflow: hidden; border: 1px solid #cbd5e1; border-radius: 12px; }
  .dm4-preview[data-theme="dark"] { --p-page: #0b1220; --p-bar: #111a2e; --p-line: #475569; --p-head: #e2e8f0; --p-card: #16213a; --p-accent: #38bdf8; }
  .dm4-bar { display: flex; gap: 6px; padding: 8px 12px; background: var(--p-bar); transition: background-color .3s; }
  .dm4-bar i { width: 8px; height: 8px; border-radius: 50%; background: #fb7185; }
  .dm4-bar i + i { background: #fbbf24; } .dm4-bar i + i + i { background: #34d399; }
  .dm4-page { display: grid; gap: 12px; padding: 16px; background: var(--p-page); transition: background-color .3s; }
  .dm4-page b { display: block; height: 8px; border-radius: 99px; background: var(--p-line); }
  .dm4-page .dm4-h { width: 66%; height: 12px; background: var(--p-head); }
  .dm4-page .dm4-short { width: 83%; }
  .dm4-cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
  .dm4-cards b { height: 48px; border-radius: 8px; background: var(--p-card); }
  .dm4-page .dm4-btn { width: 96px; height: 28px; border-radius: 6px; background: var(--p-accent); }

  @media (prefers-reduced-motion: reduce) {
    .dm4-track, .dm4-track::after, .dm4-bar, .dm4-page { transition: none; }
  }
</style>

<script>
  (function () {
    var input = document.querySelector(".dm4-input");
    if (!input) return;
    var preview = document.querySelector(".dm4-preview");
    input.addEventListener("change", function () {
      /* On a real site, set data-theme on the html element here as well, and save the value with your own storage. */
      preview.setAttribute("data-theme", input.checked ? "dark" : "light");
    });
  })();
</script>

With reduced motion: The switch knob and the preview colours change in one step without sliding or fading.

Running cost: A checkbox, one change listener and short colour transitions on a few preview blocks.

  • Copy your real colour tokens into the `--p-*` variables so the preview matches the actual page.
  • On phones the preview drops below the switch; change the 640px breakpoint to keep it side by side longer.

Performance notes

Switching a theme recalculates styles for the whole page once, which is fast for ordinary pages. Avoid putting a transition on every element's colour, because hundreds of elements fading at once can drop frames on a phone; these toggles animate only the switch itself and a few large surfaces.

To avoid a flash of the wrong theme on load, set the theme attribute in a tiny inline script in the head before the page paints, reading the saved choice and falling back to prefers-color-scheme. The toggles here keep their state in memory only, so that small head script is the one piece you add for persistence.

Questions

How do I remember the dark mode choice after a reload?

Save the chosen value with your own storage when the toggle changes, for example the browser's local storage in your site code, or a cookie if the server renders the page. On load, read it in a short inline script in the head and set the attribute before first paint. These snippets leave storage out so you can choose where it lives.

What does prefers-color-scheme do?

It is a CSS media query and a JavaScript matchMedia value that reports whether the visitor's device is set to light or dark. Use it as the default theme, and listen for its change event so a page left on system follows the device when it switches.

How do I set up dark mode in Tailwind with a toggle?

In Tailwind v3 set darkMode: "class" or "selector" in the config; in v4 add @custom-variant dark (&:where(.dark, .dark *)) to your CSS. Then the toggle adds or removes the dark class on the html element and every dark: utility follows.

Should a dark mode toggle be a switch or a button?

A two-state control can be either a switch with role="switch" and aria-checked, or a button with aria-pressed. A three-state light, dark and system control is a radio group, because exactly one of three values is chosen.

Why does my page flash white before going dark?

The theme is applied by a script that runs after the first paint. Move the code that reads the saved choice into an inline script at the top of the head, and add the color-scheme property so form controls and scrollbars match from the start.

Also in the gallery: Dark Mode Toggle Switch in React and Tailwind with System Setting and Four Styles, Photoreal Dark Mode Toggle Switch: a Ceramic Rocker on a Sunlit Plaster Wall that Dims the Room to Lamplight, CSS Toggle Switch Collection with 15 Styles on a Real Checkbox, Sizes, Disabled and RTL.

More collections: HTML and CSS Buttons: 8 Styles to Copy, Tailwind Tooltips That Work With Keyboard and Touch, Gradient Borders in CSS, Rounded and Animated. All toggles and switches. Build your site free to have a full site built around them.

Product

Who It's For

Features

Resources

Company

View Sitemap