hexcolors

Learn / Tutorials

How to add dark mode to your website with CSS variables

Support the system setting, add a manual toggle and avoid the flash of the wrong theme.

November 21, 20261 min readBy the hexcolors team

Key takeaways

  • Put every color in a CSS variable.
  • Follow the system setting, then allow a manual override.
  • Apply the saved theme before first paint to prevent a flash.

Dark mode is easiest when your colors already live in CSS variables. Here is how to respect the visitor's system setting, let them override it and remember the choice.

Step 1: Define your colors as variables

Start with the light theme as the default.

:root {
  --bg: #f6f6fa;
  --text: #0c0c14;
  --accent: #3b6cff;
}

Step 2: Override them for dark mode

Use the prefers-color-scheme media query to follow the system setting.

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #09090f;
    --text: #f4f4fa;
    --accent: #7b9bff;
  }
}

Step 3: Let people choose

Add attribute selectors so a toggle can force either theme.

:root[data-theme="dark"] {
  --bg: #09090f;
  --text: #f4f4fa;
  --accent: #7b9bff;
}

// JavaScript
document.documentElement.dataset.theme = "dark";

Step 4: Remember the choice

Store the preference so it survives a page reload.

button.addEventListener("click", () => {
  const next = document.documentElement.dataset.theme === "dark" ? "light" : "dark";
  document.documentElement.dataset.theme = next;
  localStorage.setItem("theme", next);
});

Step 5: Avoid the flash

Run a tiny inline script in the head, before the page paints, so the saved theme is applied immediately.

<script>
  try {
    var t = localStorage.getItem("theme");
    if (t) document.documentElement.dataset.theme = t;
  } catch (e) {}
</script>

Step 6: Retest contrast

Passing in light mode does not guarantee passing in dark mode. Test the dark pairs in the contrast checker, and soften saturated colors that look harsh on dark backgrounds.

Wrap up

Because every color is a variable, dark mode is just a second set of values. Our own site uses this exact pattern.

The hexcolors teamWe build free color tools and write practical guides. Follow us on X, Instagram and LinkedIn.