Learn • Create • Explore

How to Create a Dark Mode Toggle Using HTML, CSS and JavaScript

Build a keyboard-accessible theme control that follows the system and remembers a reader’s choice.

A dark mode toggle gives readers control over the colour scheme without asking them to change their device settings. The example in this guide builds a page that follows the system preference initially, lets the reader switch with a native button and remembers that choice on ordinary page loads. The colour palette lives in CSS. JavaScript manages the preference and updates the control so its visible and announced states both match what the reader sees.

Plan how the preference works

Distinguish the reader’s explicit choice from the current appearance. Someone whose device is dark at night and light in the morning may want the website to follow that schedule. Until the reader selects a theme, the system preference determines the appearance. When the reader switches the theme, save the result as their choice. If your interface offers a reset, clear that saved value and immediately apply the current system setting. This keeps a preference that changes over time from becoming a permanent override by accident.

A two-state button suits a simple page. An interface with three explicit options can use a group of radio buttons for system, light and dark. Label those options so the reader understands exactly what will be saved. Choose one approach and decide whether the default is system before designing the controls. Throughout this example the button represents dark mode being on or off, with a separate reset that restores the system setting.

The system supplies the initial theme, an explicit choice takes priority, and reset returns control to the system

Make both palettes readable

Give each colour a role such as background, surface, text, accent or border. A component then reads the same property in both themes, while the palette defines how that role looks. This is easier to maintain than putting a dark-theme copy next to every card or button. Some components need additional roles. For example, an error banner may need a surface and message colour of its own to keep both the text and border legible in each theme.

Test combinations that really appear on screen. An accent checked against the page background may be unreadable on a raised panel. Links can also look fine in their resting state while hover or visited colours lose contrast. Inspect controls, focus rings and disabled states. Use the colour contrast checker for text against its actual background. Keep a textual label for state changes because the success of the control should not depend on a colour difference alone.

Apply the CSS colour scheme property at the root to help the browser render things it styles itself, such as scrollbars and form controls. Your custom properties still control the surfaces and text you style directly. Test a page that contains a real text field in addition to the theme button. This can reveal a field background or placeholder colour that falls out of sync. Check embedded content separately because an external frame can define a palette of its own.

Theme variables supply shared colours for the page, the panel and its interactive controls

Try the complete example

Open the live preview and switch the theme twice. Check that the status line describes the appearance and that Use system updates it again. This preview may block storage because it runs inside an isolated frame. The example handles that case so the button works during the preview session. To check persistence, save the document on the same origin as a test page served over HTTP and reload it after using the toggle.

HTML example
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Theme preferences</title>
<style>
  :root {
    color-scheme: light;
    --page: #eef5fc; --surface: #fff; --text: #142b43; --accent: #034e9d;
  }
  @media (prefers-color-scheme: dark) {
    :root:not([data-theme]) {
      color-scheme: dark;
      --page: #0e1a2b; --surface: #192940; --text: #f6faff; --accent: #9bcfff;
    }
  }
  :root[data-theme="dark"] {
    color-scheme: dark;
    --page: #0e1a2b; --surface: #192940; --text: #f6faff; --accent: #9bcfff;
  }
  body { margin: 0; padding: 1rem; font: 1rem/1.55 system-ui; background: var(--page); color: var(--text); }
  main { max-width: 34rem; margin: 1rem auto; padding: 1.5rem; border-radius: 1rem; background: var(--surface); }
  button { margin: .2rem; padding: .55rem .8rem; font: inherit; color: var(--accent); background: var(--surface); border: 1px solid; border-radius: .4rem; }
  button:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; }
</style>
<main>
  <h1>Theme preferences</h1>
  <button type="button" id="toggle" aria-pressed="false" hidden>Dark mode</button>
  <button type="button" id="system" hidden>Use system</button>
  <p id="status" role="status"></p>
</main>
<script>
  const root = document.documentElement;
  const toggle = document.querySelector('#toggle');
  const reset = document.querySelector('#system');
  const status = document.querySelector('#status');
  const media = matchMedia('(prefers-color-scheme: dark)');
  const key = 'reading-theme';
  let choice = null;
  try {
    const saved = localStorage.getItem(key);
    if (saved === 'dark' || saved === 'light') choice = saved;
  } catch {}
  function appearance() {
    return choice ?? (media.matches ? 'dark' : 'light');
  }
  function render() {
    if (choice) root.dataset.theme = choice;
    else delete root.dataset.theme;
    const theme = appearance();
    toggle.setAttribute('aria-pressed', String(theme === 'dark'));
    status.textContent = theme + ' theme (' + (choice ? 'your choice' : 'system setting') + ')';
  }
  toggle.addEventListener('click', () => {
    choice = appearance() === 'dark' ? 'light' : 'dark';
    try { localStorage.setItem(key, choice); } catch {}
    render();
  });
  reset.addEventListener('click', () => {
    choice = null;
    try { localStorage.removeItem(key); } catch {}
    render();
  });
  media.addEventListener('change', render);
  render();
  toggle.hidden = false;
  reset.hidden = false;
</script>
</html>
Try it in the HTML editor

Keep the button label and state consistent

The toggle always says Dark mode. Its pressed state tells assistive technology whether dark mode is active. Changing a toggle’s label on every click can make the meaning of the pressed state harder to understand. The visible status line in this example also explains which preference supplied the current appearance. Tab to the toggle and use Space to activate it. Then try Enter and confirm the same change occurs. The focused button should remain in place when the palette changes.

The buttons start hidden so readers get working controls only after the script has set them up. When scripts are disabled, the media query still lets the page honour the device preference. The example never waits for a network request before responding. If adapting it into a shared site header, use the same key and accepted values across pages so a reader’s choice carries from the header to an article or a settings page.

The native toggle keeps its label, updates its pressed state, and displays the resulting theme

Store the choice without making storage mandatory

Local storage is shared by pages on an origin and survives an ordinary reload. A change made on an HTTPS production site is separate from a choice made on a local development server. Private browsing, browser settings and isolated previews can restrict storage. The example tries the read and writes separately. If they fail, the in-memory choice still works until the page closes. When testing, check persistence over a reload and also confirm that the control remains usable in a restricted preview.

Treat a stored string as input. Accept the two known theme names and use the system preference for anything else. This matters if you retire a third theme or change the way values are written. Confirm that clicking Use system removes the stored override. Then change the device preference with the page still open. The change listener refreshes the details on the button, and the media query applies the palette while the user follows the system.

Check early rendering and shared pages

A large site may briefly show its default palette before a saved choice is restored. Under CPU throttling, reload with a preference different from the operating system and observe whether the first visible frame matches the saved choice. If it flashes, move the small read-and-validate step earlier in the document and leave the button wiring where its elements already exist. If the site uses a Content Security Policy, follow the policy for early script delivery rather than weakening it for a theme preference.

Create a small test matrix with both system settings and both saved choices. Test a cold visit, a second visit with a saved preference and a reset. Check a narrow viewport and a page with forms. If your styling framework has nested theme selectors, inspect a dropdown or overlay appended outside the main component tree. Applying the attribute to the document root helps shared UI inherit correctly. Then run a final keyboard pass to ensure the focus indicator remains easy to see in both palettes.

Edit the colours in the CSS editor and validate the switch in the JavaScript editor. The MDN colour scheme preference reference describes how CSS receives the operating system’s theme choice.

Review graphics and browser chrome

Some logos or illustrations contain text baked into an image. Hold the image against both surfaces and make sure its important features remain visible, including transparent edges and fine strokes. You can keep the image on a deliberate surface or provide a suitable variant. Avoid automatically inverting all images. Photographs and product colours carry information, and an image that has already been prepared for dark mode can become harder to read when a global filter inverts it a second time.

Also check how the page behaves in forced colours mode, which can substitute a high contrast system palette. Borders and outlines are often more dependable than a colour-only change or a box shadow in that environment. Leave browser colour adjustments enabled unless a specific graphic requires otherwise. Test the theme control while zoomed as well. The label should remain available and the status should be readable on a line below if the controls wrap. These checks help keep the preference usable in a range of reading conditions.

Related tools

Continue learning