Skip to main content

Design and frontend · Intermediate · 20 min

How to Add Dark Mode to a Website with CSS Variables

By Padding · Updated 15 Nov 2026
Modern browsers · CSS Color Module Level 5 (light-dark()) · checked in Chromium 159 · Node.js 26

You will define your colours once as CSS custom properties, switch them with light-dark() and the user's system setting, add a toggle button that remembers the choice without a flash on reload, and check the text contrast of both themes with a short script.

On this page

Many people set their phone or computer to a dark appearance, and browsers pass that choice to websites. A site that ignores it can blind a reader at night. A site that follows it needs two sets of colours, and the clean way to manage two sets is to name every colour once, as a CSS custom property, and change only the values.

You will build a small page and give it a light and a dark theme with a few lines of CSS. By default it follows the system setting. A button lets the reader override that, and the choice is remembered. Along the way you will check that the text stays readable in both themes, using the contrast rule in the Web Content Accessibility Guidelines (WCAG) 2.2.

Step 1 · Build the page with colour variables

Create a folder with an HTML file and a stylesheet. The page has a heading, text, a link, a card, and a form field and button, because form controls are where dark mode usually goes wrong:

Bash
mkdir -p ~/theme-demo
cd ~/theme-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="color-scheme" content="light dark">
  <script>try { var t = localStorage.getItem("theme"); if (t === "light" || t === "dark") document.documentElement.dataset.theme = t; } catch (e) {}</script>
  <title>Theme demo</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header class="bar">
    <strong>Theme demo</strong>
    <button id="theme-toggle" type="button" aria-pressed="false">Dark mode</button>
  </header>
  <main>
    <h1>Readable in any light</h1>
    <p>Body text uses <code>var(--text)</code>. <span class="muted">Secondary text is a little softer.</span>
      Links use the <a href="#more">accent colour</a>.</p>
    <section class="card">
      <h2>A card</h2>
      <p>Cards sit on a slightly different surface so they stand out from the page.</p>
    </section>
    <form>
      <label for="email">Email</label>
      <input id="email" type="email" placeholder="you@example.com">
      <button type="button" class="primary">Subscribe</button>
    </form>
  </main>
  <script src="theme.js"></script>
</body>
</html>
HTML

The page already contains two script tags for the later steps: a one-line script in the <head> that restores a saved choice, and theme.js at the end of the <body>. The browser logs a harmless 404 for theme.js until you create it in the next step. The color-scheme meta tag tells the browser, before the stylesheet has loaded, that the page supports both schemes. That avoids a white flash while a dark page loads. Now write the stylesheet. Every colour is a custom property on :root, and the rest of the CSS only refers to the names:

Bash
cat > style.css <<'CSS'
:root {
  color-scheme: light dark;

  --bg:       light-dark(#ffffff, #12161c);
  --surface:  light-dark(#f3f5f8, #1b222b);
  --border:   light-dark(#c4ccd6, #3a4552);
  --text:     light-dark(#1b1f24, #e6e9ee);
  --muted:    light-dark(#57606a, #a3adb8);
  --accent:   light-dark(#0b5cad, #6cb2ff);
  --on-accent: light-dark(#ffffff, #0b1118);
}

body { margin: 0; background: var(--bg); color: var(--text); font: 1rem/1.6 system-ui, sans-serif; }
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.bar { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 1rem;
       background: var(--surface); border-bottom: 1px solid var(--border); }
.muted { color: var(--muted); }
a { color: var(--accent); }
code { background: var(--surface); padding: 0.1em 0.3em; border-radius: 0.25rem; }
.card { background: var(--surface); border: 1px solid var(--border); border-radius: 0.5rem; padding: 1rem; margin: 1rem 0; }
label { display: block; margin-bottom: 0.25rem; }
input { padding: 0.5rem; border: 1px solid var(--border); border-radius: 0.25rem; }
button { padding: 0.5rem 0.75rem; border: 1px solid var(--border); border-radius: 0.25rem; cursor: pointer; }
button.primary { background: var(--accent); color: var(--on-accent); border-color: transparent; }
CSS

Two features do the work. light-dark(a, b) returns a when the page is using a light colour scheme and b when it is using a dark one, so each variable holds both of its values in one place. It only works when color-scheme includes both, which is what color-scheme: light dark on :root declares. That property also tells the browser to draw its own parts of the page in the matching scheme: the default colours of form controls, scrollbars and the page background before your CSS applies. light-dark() is supported by all current browsers and counted as Baseline 2024 by MDN, meaning it works in browsers released since May 2024.

Check it worked

Open index.html in a browser: xdg-open index.html on Linux, open index.html on macOS, or drag the file onto a browser window. With your system in its light appearance you see a white page with dark text, a pale card and a blue link. Change your system appearance to dark, which is in System Settings on macOS and Windows and in Settings on Android and iOS. The page switches by itself, with no reload needed in current browsers, to a near-black background, light text, and a light-blue link. Notice that the text input also turns dark.

Troubleshooting

If the page stays light in a dark system, check that color-scheme: light dark is on :root and not misspelled, and that your browser is recent enough for light-dark(). In Chrome and Edge you can test without changing your system: open DevTools, press Ctrl+Shift+P (Cmd+Shift+P on macOS), type "prefers-color-scheme" and choose the rendering emulation. Firefox has a similar option in its inspector's colour-scheme buttons.

Step 2 · Add a button that overrides the system setting

Some readers want a dark page in a light system, or the reverse. Give them a button. The page picks its scheme from the color-scheme property, so the override is just a different value of that property on <html>, set from an attribute:

Bash
cat >> style.css <<'CSS'

:root[data-theme="light"] { color-scheme: light; }
:root[data-theme="dark"]  { color-scheme: dark; }
CSS
cat > theme.js <<'JS'
const root = document.documentElement;
const button = document.getElementById("theme-toggle");

function currentTheme() {
  if (root.dataset.theme) return root.dataset.theme;
  return matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
}

button.setAttribute("aria-pressed", String(currentTheme() === "dark"));

button.addEventListener("click", () => {
  const next = currentTheme() === "dark" ? "light" : "dark";
  root.dataset.theme = next;
  button.setAttribute("aria-pressed", String(next === "dark"));
  try {
    localStorage.setItem("theme", next);
  } catch {
    // Storage can be blocked, so the choice just lasts until the page is closed.
  }
});
JS

There is no second palette to maintain: forcing color-scheme: dark on the root makes every light-dark() pick its second value. The button is a toggle button, a button that is on or off, so it carries aria-pressed and screen readers announce "pressed" or "not pressed". The try and catch around localStorage matter because browsers can block storage, for example in some private windows.

Check it worked

Reload the page in the browser and click the Dark mode button. It is a toggle: pressed means dark. If your system is already dark, the button starts pressed, and clicking it switches the page to light. The page changes at once, and the button's pressed state flips.

Step 3 · Remember the choice without a flash

The click handler stores the choice, but without help the page would start in the system theme until the script runs, and a reader who chose dark in a light system would see a white flash on each load. That is why the <head> of your page, from the first step, has a tiny inline script that sets the attribute before the browser paints anything. Look at it:

Bash
grep -n 'localStorage.getItem' index.html

The script is small, runs before the stylesheet and the body exist, and has no dependencies, so it blocks nothing noticeable. It only accepts the two known values. Putting it in theme.js at the end of the body would work too, but the page would flash.

Check it worked

The grep shows the line number of the inline script, which sits in the <head>. In the browser, click the button to pick the opposite of your system theme, then reload. The page loads in the chosen theme with no flash. Your choice is kept in the browser's localStorage under the key theme, so it lasts across visits on the same device and browser.

Step 4 · Check the contrast of both themes

A dark theme that is stylish and unreadable fails the people it was meant for. WCAG 2.2 success criterion 1.4.3, Contrast (Minimum), requires a contrast ratio of at least 4.5:1 between normal-size text and its background, and 3:1 for large text (at least 24 CSS pixels, or 18.66 pixels bold). The ratio comes from each colour's relative luminance, a formula in the WCAG definition. Write a script that applies it to your palette, so a colour change that breaks the rule fails loudly:

Bash
cat > contrast.mjs <<'JS'
const palette = {
  light: { bg: "#ffffff", surface: "#f3f5f8", text: "#1b1f24", muted: "#57606a", accent: "#0b5cad", onAccent: "#ffffff" },
  dark:  { bg: "#12161c", surface: "#1b222b", text: "#e6e9ee", muted: "#a3adb8", accent: "#6cb2ff", onAccent: "#0b1118" },
};

function luminance(hex) {
  const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
    .map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
  return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}

function ratio(a, b) {
  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
  return (hi + 0.05) / (lo + 0.05);
}

const pairs = [
  ["text", "bg"], ["text", "surface"], ["muted", "bg"], ["muted", "surface"],
  ["accent", "bg"], ["accent", "surface"], ["onAccent", "accent"],
];

let failed = false;
for (const [scheme, colours] of Object.entries(palette)) {
  for (const [fg, bg] of pairs) {
    const value = ratio(colours[fg], colours[bg]);
    const ok = value >= 4.5;
    failed ||= !ok;
    console.log(`${scheme.padEnd(5)} ${fg.padEnd(8)} on ${bg.padEnd(7)} ${value.toFixed(2)}:1 ${ok ? "ok" : "FAIL"}`);
  }
}
process.exitCode = failed ? 1 : 0;
JS
node contrast.mjs

Check it worked

The script prints 14 lines, one for each pair of colours in each theme, and every line ends in ok. For example, the light theme's text on its page background is about 16:1, and its secondary text on the page is about 6.4:1. A line that ends in FAIL is below 4.5:1. If you change a colour in style.css, copy the new value into the palette object and run the script again. The script's palette repeats the values from the stylesheet, so keep the two in step.

Contrast is one part of readable colour. Do not use colour as the only signal, such as red text alone for an error, since WCAG 2.2 success criterion 1.4.1, Use of Color, asks for another cue, and test the borders of inputs against their background too, at 3:1 under criterion 1.4.11, Non-text Contrast.

Step 5 · Handle images, shadows and older browsers

Variables fix colours but not everything. These cases come up in most sites:

  • Photographs usually look fine in both themes. A logo with a transparent background and dark lettering does not. Serve a second version of it with <picture> and <source media="(prefers-color-scheme: dark)" srcset="logo-dark.svg">.
  • Shadows disappear on dark backgrounds. Use a lighter border, or put the shadow in a variable with light-dark(), such as --shadow: light-dark(0 1px 3px rgb(0 0 0 / 20%), none).
  • Avoid pure black backgrounds, which make light text glare, and pure white text on them. The dark palette above uses near-black and off-white.
  • For browsers older than May 2024 that do not know light-dark(), add a fallback inside an @supports not block. Custom properties accept any text when the stylesheet is parsed, so a browser without light-dark() would take --bg: light-dark(...) as valid and then fail when it uses it. Wrapping the fallback in @supports applies it only in those browsers. Put it after the main :root block, and repeat the pair of lines for every variable in that block, not only the two shown:
CSS
@supports not (color: light-dark(white, black)) {
  :root { --bg: #ffffff; --text: #1b1f24; }
  @media (prefers-color-scheme: dark) {
    :root { --bg: #12161c; --text: #e6e9ee; }
  }
}

The manual toggle will not override these fallback values, so for those browsers it changes nothing. Decide whether the old-browser share of your audience justifies the extra lines.

Step 6 · Clean up

Remove the demo folder:

Bash
cd ~
rm -rf ~/theme-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.