Skip to main content
CodingMarble

Code snippets

Dark Mode With CSS Variables: A Practical Guide

Define your colours once as CSS custom properties on :root, override them inside a prefers-color-scheme: dark query, and let a data-theme attribute on the html element take priority when the visitor picks a theme manually. A tiny inline script in the head applies the saved choice before the first paint so the page never flashes the wrong theme.

By CodingMarble · Published · 4 min read

A laptop showing code on a busy desk
Photo: Christopher Gower on Unsplash

Start with colour tokens on :root

Dark mode becomes easy when no component hard-codes a colour. Instead of writing background: #ffffff in forty places, define named values once and refer to them everywhere. CSS custom properties, which you declare with a double-dash name and read with var(), cascade and inherit like any other property, so changing them in one place re-themes everything beneath.

Name tokens by role, not by appearance. A name like --surface describes what the colour is for and stays correct in both themes. A name like --white would be wrong the moment dark mode turns it near-black. Keep the set small and resist adding a new token for every one-off colour, since each extra name is another value that needs a dark counterpart. A page background, a raised surface, text, muted text, a border, and an accent are enough for most sites.

CSS· Light theme tokens and components that only use tokens
:root {
  color-scheme: light;
  --bg: #ffffff;
  --surface: #f3f4f6;
  --text: #111827;
  --text-muted: #4b5563;
  --border: #d1d5db;
  --accent: #1d4ed8;
  --accent-text: #ffffff;
}

body {
  background: var(--bg);
  color: var(--text);
}

.card {
  background: var(--surface);
  border: 1px solid var(--border);
}

.btn {
  background: var(--accent);
  color: var(--accent-text);
}

The color-scheme property tells the browser which themes the page supports so it can adjust built-in UI to match: form controls, scrollbars and the default canvas colour. Without it, a dark page can still show a bright native scrollbar or white form fields.

Follow the visitor's system setting

The prefers-color-scheme media query reports whether the operating system or browser is set to light or dark. Redefine the tokens inside it and every component updates, because the components already read the tokens.

CSS· Dark tokens applied automatically from the system preference
@media (prefers-color-scheme: dark) {
  :root {
    color-scheme: dark;
    --bg: #0f172a;
    --surface: #1e293b;
    --text: #f1f5f9;
    --text-muted: #cbd5e1;
    --border: #475569;
    --accent: #60a5fa;
    --accent-text: #0f172a;
  }
}

Notice that the dark palette is not a simple inversion. Pure black backgrounds with pure white text produce harsh contrast that many people find tiring to read, so softer dark blues and off-white text are common choices. The accent is lighter than in the light theme because a dark blue on a dark surface would be hard to see, and the text on the accent flips to dark to keep the button readable.

Add a manual toggle with data-theme

Many visitors want to override the system setting for one site. The common pattern is a data-theme attribute on the html element. Because an attribute selector with :root is more specific than :root alone, it overrides the defaults. Dark tokens now need to exist in two places: the media query, for people who have not chosen, and the attribute, for people who have.

To avoid duplicating the dark values, define them once on the attribute and have the media query apply only when no explicit light choice was made.

CSS· One set of dark values, reachable by attribute or by system preference
:root[data-theme="dark"] {
  color-scheme: dark;
  --bg: #0f172a;
  --surface: #1e293b;
  --text: #f1f5f9;
  --text-muted: #cbd5e1;
  --border: #475569;
  --accent: #60a5fa;
  --accent-text: #0f172a;
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    color-scheme: dark;
    --bg: #0f172a;
    --surface: #1e293b;
    --text: #f1f5f9;
    --text-muted: #cbd5e1;
    --border: #475569;
    --accent: #60a5fa;
    --accent-text: #0f172a;
  }
}

CSS cannot share declarations between a media query and a selector without a preprocessor, so a small duplication is the price of this approach. If that bothers you, generate both blocks from one source in your build step. With the CSS in place, a button toggles the attribute and saves the choice.

HTML· A toggle button that reflects its state to assistive technology
<button type="button" id="theme-toggle" aria-pressed="false">
  Dark mode
</button>

<script>
  (function () {
    var root = document.documentElement;
    var button = document.getElementById("theme-toggle");

    function isDark() {
      var saved = root.getAttribute("data-theme");
      if (saved) return saved === "dark";
      return window.matchMedia("(prefers-color-scheme: dark)").matches;
    }

    button.setAttribute("aria-pressed", String(isDark()));

    button.addEventListener("click", function () {
      var next = isDark() ? "light" : "dark";
      root.setAttribute("data-theme", next);
      button.setAttribute("aria-pressed", String(next === "dark"));
      try { localStorage.setItem("theme", next); } catch (e) {}
    });
  })();
</script>

The button uses aria-pressed because it is a two-state toggle, and its label stays constant so the meaning does not flip with the state. The try and catch around localStorage matters, since storage can throw in private browsing or when a user has blocked site data. The page should still work when saving fails.

Avoid the flash of the wrong theme

If the saved theme is read by a script at the end of the page, the browser paints the default theme first and then switches, which shows as a visible flash for returning visitors. The fix is a tiny script in the head that sets the attribute before the body is rendered. It must be synchronous and small, so it blocks nothing meaningful.

HTML· Place this in the head, before your stylesheet
<script>
  try {
    var saved = localStorage.getItem("theme");
    if (saved === "light" || saved === "dark") {
      document.documentElement.setAttribute("data-theme", saved);
    }
  } catch (e) {}
</script>
<link rel="stylesheet" href="/styles.css">

It reads the saved value, validates it against the two allowed strings so a tampered value does nothing, and sets the attribute on the root element, which already exists at that point. If nothing is saved, the attribute is left off and the media query handles the system preference with no script involved. If your site has a strict Content Security Policy, you will need a nonce or hash to allow this inline script.

Images, shadows and other details

Colours are only part of the work. Bright images on a dark page can glare, and shadows that look natural on white barely register on a dark surface. A few small rules cover most of it.

CSS· Dim images slightly and tune shadows per theme
:root {
  --shadow: 0 2px 8px rgb(0 0 0 / 0.12);
}

:root[data-theme="dark"] {
  --shadow: 0 2px 8px rgb(0 0 0 / 0.5);
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --shadow: 0 2px 8px rgb(0 0 0 / 0.5);
  }
}

.card { box-shadow: var(--shadow); }

:root[data-theme="dark"] img:not([src$=".svg"]) {
  filter: brightness(0.9);
}
  • Shadows: make them stronger in dark mode, or use a slightly lighter surface and a visible border to show elevation instead.
  • Logos and icons: SVGs that use currentColor follow the text colour automatically. Raster logos with dark text may need a separate light version, swapped with a picture element and a prefers-color-scheme media attribute.
  • Transitions: avoid animating every colour on theme switch. If you add a short colour transition, respect prefers-reduced-motion.
  • Third-party widgets such as embeds and maps often ignore your tokens, so test them in both themes.

Test contrast in both themes

Each theme needs checking on its own, because a pairing that passes in light mode can fail in dark. Normal body text should reach a contrast ratio of 4.5:1 against its background under WCAG, large text needs 3:1, and meaningful interface boundaries and focus rings also need 3:1. Test text, muted text, links, borders, placeholder text and disabled states, not only the headline colours.

Your browser's developer tools can show the contrast ratio of a selected element, and you can emulate the system preference from the rendering panel without changing your operating system. Toggle the attribute by hand as well, to confirm the override path works. Record the results next to your tokens so the next person who edits a colour knows which pairings were checked. Finally, try the page with the saved theme cleared, with a saved light choice on a dark system, and with a saved dark choice on a light system, since those three cases are where theme bugs usually hide.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.