Skip to content
Velloreth
Web Development 6 min read

Dark Mode in CSS: A Practical Implementation

Implement dark mode with prefers-color-scheme and custom properties. Learn the contrast, the images, and the flash of the wrong theme.

By

The system preference

@media (prefers-color-scheme: dark) {
  body {
    background: #121212;
    color: #e0e0e0;
  }
}

This is the right default. The user has already expressed a preference in their operating system, and the page should respect it.

The three values are light, dark, and no-preference. The last is rare, and a light default is a reasonable fallback.

Custom properties

A theme is a set of values, not a set of rules.

:root {
  --bg: #ffffff;
  --text: #1a1a1a;
  --muted: #666666;
  --border: #e0e0e0;
  --accent: #2563eb;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #121212;
    --text: #e0e0e0;
    --muted: #a0a0a0;
    --border: #2a2a2a;
    --accent: #60a5fa;
  }
}

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

The rules do not change, only the values. This is the whole benefit: one set of rules, two sets of values.

The accent needs a different value in dark mode. A blue that is readable on white is too dark on a dark background.

A manual toggle

A toggle needs a class on the root, and the class must win over the media query.

:root {
  --bg: #ffffff;
  --text: #1a1a1a;
}

:root[data-theme="dark"] {
  --bg: #121212;
  --text: #e0e0e0;
}

@media (prefers-color-scheme: dark) {
  :root:not([data-theme="light"]) {
    --bg: #121212;
    --text: #e0e0e0;
  }
}

The :not([data-theme="light"]) is the key. It lets an explicit light choice override the system preference.

The three states: no attribute (follow the system), data-theme="dark", and data-theme="light".

Avoiding the flash

The theme must be applied before the first paint, or the page flashes the wrong colour.

<script>
  (function () {
    const stored = localStorage.getItem('theme');
    if (stored) {
      document.documentElement.dataset.theme = stored;
    }
  })();
</script>

Put it in the head, before the body. A script at the end of the body runs after the first paint, which is too late.

The script must be inline, because an external script is a network request that delays the paint.

Keep it tiny. It runs on every page load, and it blocks the render.

The toggle

function toggleTheme() {
  const root = document.documentElement;
  const current = root.dataset.theme
    ?? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
  const next = current === 'dark' ? 'light' : 'dark';
  root.dataset.theme = next;
  localStorage.setItem('theme', next);
}

Persist the choice, so it survives a reload.

Respect the system preference as the default, so a user who has never toggled gets the right theme.

A three-state toggle (system, light, dark) is more correct and more complex. A two-state toggle that starts from the system preference is a reasonable compromise.

Contrast

Dark mode is not an inversion.

A pure black background with pure white text has a contrast ratio of 21:1, which is too high. It causes halation for some readers, especially with astigmatism, and it is tiring over a long session.

Use a dark grey such as #121212 and an off-white text such as #e0e0e0. The contrast is still well above the WCAG AA threshold of 4.5:1, and it is easier to read.

Check the contrast in both themes. A colour that passes in light mode may fail in dark mode, and the accent colour is the usual culprit.

Do not use pure white for a large area of text. A slightly reduced white is easier on the eye.

Images and media

Do not invert an image. A photo of a person becomes a negative, which is unsettling.

A slight brightness reduction is a reasonable treatment for a bright image on a dark background.

@media (prefers-color-scheme: dark) {
  img:not([data-no-dim]) {
    filter: brightness(0.9);
  }
}

A diagram with a white background is the harder case. The options are a separate asset, a transparent background, or a container with a light background.

.diagram {
  background: #ffffff;
  padding: 1rem;
  border-radius: 0.5rem;
}

An SVG can use currentColor, so it adapts to the theme automatically.

Form controls and scrollbars

:root {
  color-scheme: light dark;
}

color-scheme tells the browser which schemes the page supports, so it styles a form control, a scrollbar, and the default background correctly.

Without it, a native select or a scrollbar stays light in dark mode, which looks broken.

Set it on the root, and the browser handles the rest.

Testing a theme

A theme is a set of values, and the way to verify it is to look at the page in both modes rather than to reason about the colours. The checks that catch the most problems are the contrast of the body text, the contrast of the muted text, the contrast of the accent against the background, and the appearance of a form control and a scrollbar. The muted text is the usual failure, because a grey that is readable on white is often too dark on a dark background, and the accent is the second, because a blue that passes on white can fail on a dark surface. The images are the third, because a diagram with a white background looks like a hole in the page unless it is given a light container. The most reliable test is to switch the operating system theme and reload the page, which also confirms that the inline script applies the theme before the first paint and that there is no flash of the wrong colour.

Practical guidance

  • Use prefers-color-scheme as the default.
  • Use custom properties for the theme values.
  • Set the theme in an inline head script to avoid a flash.
  • Persist the choice in localStorage.
  • Use a dark grey, not pure black.
  • Check the contrast in both themes.
  • Do not invert an image.
  • Set color-scheme for the form controls.
  • Give the accent a different value in dark mode.

For the related guides, see css-custom-properties and css-units-explained. For the broader context, css-pseudo-classes-guide and css-selectors-cheatsheet.

Quotable summary

prefers-color-scheme detects the user’s system preference and it is the right default, and custom properties make a theme a set of values rather than a set of rules, so the rules do not change and only the values do. A theme toggle should persist the choice and respect the system preference as the default, and the theme must be set in an inline script in the head before the body renders, or the page flashes the wrong colour. Dark mode is not an inversion: a pure black background with pure white text has too much contrast and causes halation for some readers, so use a dark grey such as #121212 and an off-white text. Set the color-scheme property so the browser styles a form control and a scrollbar correctly, and give the accent colour a different value in dark mode.

Frequently asked questions

How do I detect dark mode in CSS?
Use the prefers-color-scheme media query, which matches dark or light based on the user's system setting.
How do I avoid a flash of the wrong theme?
Set the theme in an inline script in the head, before the body renders, so the correct class is applied before the first paint.
What is the color-scheme property?
A CSS property that tells the browser which color schemes the page supports, so it styles a form control, a scrollbar, and the default background correctly.
Should dark mode use pure black?
No. A pure black background with pure white text has too much contrast and causes halation for some readers. Use a dark grey such as #121212 and an off-white text.
How do I make images work in dark mode?
Use a slightly reduced brightness for a photo, or provide a separate asset. Do not invert an image, which produces a strange result.
How do I persist the theme choice?
Store it in localStorage, and read it in an inline script before the page renders so there is no flash.