🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

CSS Dark Mode: Color Schemes, Tokens, and Theme Switching

Web StylesđŸŸĸ Free Lesson

CSS Dark Mode: Color Schemes, Tokens, and Theme Switching

Dark mode used to be a novelty toggle. It is now a baseline expectation: operating systems expose a system-wide preference, users with light sensitivity set it by default, and OLED phones genuinely save battery on dark pixels. Yet most dark mode implementations fail in predictable ways — a flash of white on load, unreadable gray-on-gray text, images that look like mud, and a toggle that forgets the user's choice. Getting it right is less about one CSS property and more about architecture: design tokens first, media queries second, JavaScript third.

Why filter: invert is the wrong tool

The naive implementation applies filter: invert(1) hue-rotate(180deg) to the whole page and calls it done. Inverted photos look like negatives, brand colors drift into the wrong hue family, and user-generated content — charts, product images, avatars — inverts along with everything else. A proper dark theme redefines the palette, not the pixels. Treat every color in your UI as a token, then provide a light value and a dark value for each token. Components never hard-code colors; they reference tokens.

Token roleLight valueDark valueNotes
--color-bg#ffffff#0b0f14Slightly off-black reduces halation on OLED
--color-surface#f8fafc#151b23Cards and panels sit above the background
--color-text#0f172a#e2e8f0Pure white on pure black strains the eye
--color-muted#64748b#94a3b8Raise lightness to keep muted text readable
--color-border#e2e8f0#2a3441Borders must stay visible on dark surfaces
--color-accent#2563eb#60a5faLighten accents; dark blues vanish on dark bg

The pattern in the table is deliberate: dark mode is not "the same values, inverted". Elevation inverts too — light UI adds shadows to lift cards, dark UI adds lighter surfaces, because shadows are invisible on a dark canvas.

The color-scheme property does half the work

Before any custom properties, declare which schemes your page supports:

:root {
  color-scheme: light dark;
}

@supports (prefers-color-scheme: dark) {
  :root {
    --color-bg: #ffffff;
    --color-text: #0f172a;
  }
}

@media (prefers-color-scheme: dark) {
  :root {
    --color-bg: #0b0f14;
    --color-surface: #151b23;
    --color-text: #e2e8f0;
    --color-muted: #94a3b8;
    --color-border: #2a3441;
    --color-accent: #60a5fa;
  }
}

body {
  background: var(--color-bg);
  color: var(--color-text);
  transition: background-color 0.2s ease, color 0.2s ease;
}

::selection {
  background: var(--color-accent);
  color: var(--color-bg);
}

color-scheme: light dark tells the browser it may paint native form controls, scrollbars, and the default canvas in the user's preferred scheme. Without it, your page goes dark while the date picker, select dropdown, and scrollbar stay glaring white. Setting color-scheme: dark inside the dark media query (or on a [data-theme="dark"] element) keeps those UA components in sync.

Following the system, then letting users override it

prefers-color-scheme covers users who never touch your toggle. A manual toggle covers users who want dark on a light OS or vice versa — a common request among developers who work in dark editors all day but use a light desktop. The two combine through specificity: define the system-driven values in the media query, then let an explicit attribute win.

The toggle button itself must follow the same tokens as the rest of the UI, and its accessible name should describe the action, not the current state — "Switch to dark theme" is better than "Dark mode: on", because the name tells keyboard and screen-reader users what pressing the button will do. Pair it with a visible icon so sighted users never have to read the label, and remember that aria-pressed or a changing accessible name are both valid patterns; pick one and stay consistent across your product.

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

:root[data-theme="dark"] {
  color-scheme: dark;
  --color-bg: #0b0f14;
  --color-surface: #151b23;
  --color-text: #e2e8f0;
  --color-muted: #94a3b8;
  --color-border: #2a3441;
  --color-accent: #60a5fa;
}

:root[data-theme="light"] {
  color-scheme: light;
  --color-bg: #ffffff;
  --color-surface: #f8fafc;
  --color-text: #0f172a;
  --color-muted: #64748b;
  --color-border: #e2e8f0;
  --color-accent: #2563eb;
}

The :not([data-theme="light"]) guard is what makes the override work: a user who explicitly picks light on a dark OS must not have the media query re-darken their page. Store the choice in localStorage, and — critically — apply it in an inline script in the document head before first paint. A toggle that runs after hydration produces the dreaded white flash, and every user notices it, even the ones who never change the setting.

Persisting three states — light, dark, and system — is friendlier than a binary toggle. "System" removes the attribute and lets prefers-color-scheme decide as the OS setting changes during the day; explicit light and dark pin the theme regardless of the OS. Whatever states you support, document them in the toggle's tooltip and default new visitors to system, which is what most people expect on a first visit.

Surfaces, shadows, and images in the dark

Three rules separate polished dark themes from washed-out ones. First, replace drop shadows with surface elevation: a card on #0b0f14 needs --color-surface: #151b23 and a hairline border, not box-shadow: 0 4px 12px rgba(0,0,0,0.15), which is invisible. Second, treat large solid fills of your accent color as danger zones — a full-width #2563eb banner vibrates against dark text nearby; drop the accent's lightness or invert the text color. Third, handle imagery explicitly:

@media (prefers-color-scheme: dark) {
  .photo {
    filter: brightness(0.85) contrast(1.05);
  }

  .logo--dark-variant {
    content: url("/logo-light.svg");
  }

  .chart svg .axis-line {
    stroke: var(--color-border);
  }
}

Some images need a dedicated dark-mode asset — logos with transparent backgrounds and dark fills disappear entirely. Others tolerate a modest brightness reduction. And charts or diagrams built from inline SVG should pull stroke and fill colors from tokens so they retheme with the page.

Transitions, reduced motion, and the flash problem

Transitioning background-color and color on body makes theme switches feel intentional rather than jarring. Two caveats: never apply a blanket * { transition: ... } rule to animate every element on the page, because it forces style recalculations across the whole tree during the switch and can visibly lag on large apps; scope transitions to the elements that actually change — body, headers, cards. And respect the user's motion preference:

@media (prefers-reduced-motion: reduce) {
  body {
    transition: none;
  }
}

The same media query you use for reduced-motion elsewhere applies here: some users get dizzy from large color shifts, and a 200ms cross-fade becoming an instant swap costs nothing.

Keep the transition scoped a step further for print and for embeds: a printing page does not need animated background changes, and an iframe theme switch should animate only inside its own bounds. Scoping with a wrapper class also prevents the transition from firing on initial page load, which otherwise tints the first paint with a subtle flash of intermediate color on slower devices.

Contrast rules specific to dark palettes

The WCAG contrast math does not change in dark mode, but the mistakes do. Light mode's muted gray #94a3b8 on white scores comfortably; the same hex on #0b0f14 may fall short. Recalculate every text token against its actual dark background. Avoid pure #ffffff text on pure #000000 backgrounds — the high-frequency edge causes halation, where text appears to glow and blur for many readers; #e2e8f0 on #0b0f14 is both calmer and still comfortably above 4.5:1. And check your accent links: #2563eb on near-black fails; #60a5fa passes.

Common Mistakes

Applying filter: invert to the whole page, which ruins photos, charts, and embedded content.

Fix: Redefine color tokens per scheme; only ever filter specific decorative assets that you control.

Forgetting color-scheme, leaving native controls and scrollbars light while the page is dark.

Fix: Set color-scheme: light dark on :root and flip it to dark on your dark theme.

Letting the prefers-color-scheme media query override an explicit user choice of light on a dark system.

Fix: Guard the media query with :root:not([data-theme="light"]) so an explicit attribute always wins.

Showing a white flash before JavaScript applies the saved theme.

Fix: Run a tiny inline script in the head that reads localStorage and sets data-theme before first paint.

Reusing light-mode muted grays and accents on dark backgrounds without rechecking contrast.

Fix: Lighten muted text and accent colors for dark surfaces, and re-run contrast checks on every token pair.

Best Practices

  • Define every UI color as a custom property; no component should contain a raw hex value.
  • Model elevation with lighter surfaces and subtle borders in dark mode instead of drop shadows.
  • Scope theme transitions to body and surface elements rather than a universal * transition rule.
  • Provide dark-aware variants for logos and illustration assets that contain baked-in dark fills.
  • Support the toggle from day one, persist it, and apply it pre-paint to avoid the flash of wrong theme.

Key Takeaways

  • Dark mode redefines a token palette; it does not invert pixels — photos, charts, and brand colors must survive independently.
  • color-scheme keeps native controls, scrollbars, and the canvas in sync with your theme; ship it on :root.
  • prefers-color-scheme handles the default; a data-theme attribute with a :not() guard handles explicit overrides.
  • Elevation inverts: use lighter surfaces and borders on dark backgrounds, where shadows stop working.
  • Recheck every contrast pair — muted grays and blue accents that pass on white frequently fail on near-black.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement