Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add night mode by combining the browser’s prefers-color-scheme media feature with a coordinated set of CSS color variables. Declare light dark support in the document head, set color-scheme on the root element, define light and dark tokens, and optionally add a saved manual switch whose choice takes precedence over the operating-system preference.

1. Declare dark-mode support before the page paints

Put this element as early as possible in <head>, before your stylesheets:

<meta name="color-scheme" content="light dark">

The declaration tells the browser that the document supports both schemes. It allows browser-provided UI—such as the canvas, scrollbars, form controls and other native controls—to adapt. It does not recolor components designed by your CSS; those still need explicit theme rules.

Also set the property on the root element:

:root {
  color-scheme: light dark;
}

Placing the meta element before style information helps reduce a flash in which native controls are painted in the wrong scheme.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

2. Build the two palettes with CSS custom properties

Central tokens keep every component on the same palette and make later adjustments safer. Define a complete light baseline, then replace the tokens in a dark media query:

:root {
  color-scheme: light dark;
  --page-bg: #ffffff;
  --page-text: #202124;
  --surface: #f3f4f6;
  --surface-raised: #ffffff;
  --border: #c7cbd1;
  --link: #0757a6;
  --focus: #0b57d0;
  --muted: #5f6368;
}

@media (prefers-color-scheme: dark) {
  :root {
    --page-bg: #171717;
    --page-text: #f2f2f2;
    --surface: #292929;
    --surface-raised: #202124;
    --border: #5f6368;
    --link: #8ab4f8;
    --focus: #a8c7fa;
    --muted: #bdc1c6;
  }
}

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

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

.card--raised {
  background: var(--surface-raised);
}

a { color: var(--link); }

:focus-visible {
  outline: 3px solid var(--focus);
  outline-offset: 2px;
}

.text-muted { color: var(--muted); }

The hex values above are illustrative. Choose colors for your brand, then evaluate each foreground/background pair in both schemes. Include text, links, borders, icons, placeholders, disabled states, selection colors, focus indicators, alerts, tables and code blocks—not just the page background.

3. Let the system preference remain the default

prefers-color-scheme reflects the light or dark preference selected in the operating system or user agent. It is broadly available in modern browsers; MDN records availability since January 2020. With no saved site choice, the media query above follows that preference automatically.

The system setting can change while a page is open. If JavaScript reads the preference, subscribe to its change event:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const media = window.matchMedia('(prefers-color-scheme: dark)');

function applySystemTheme() {
  if (!document.documentElement.dataset.theme) {
    document.documentElement.classList.toggle('system-dark', media.matches);
  }
}

applySystemTheme();
media.addEventListener('change', applySystemTheme);

In this example, the class is only an optional hook for scripts or components. CSS can usually respond directly through the media query. A manually pinned theme should not be replaced when the operating system changes.

4. Add a manual light/dark override that is remembered

A control is useful when a visitor wants a choice different from the device setting. Store only an explicit override; absence of a value means “follow system.” A two-state control (system versus pinned alternate) is the pattern recommended in Google Chrome’s modern web guidance, although a product may instead expose separate System, Light and Dark choices.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Markup

<button id="theme-toggle" type="button" aria-pressed="false">
  Use dark mode
</button>

CSS precedence

Put the override selectors after the media query so an explicit attribute wins over the system default:

[data-theme="light"] {
  color-scheme: light;
  --page-bg: #ffffff;
  --page-text: #202124;
  --surface: #f3f4f6;
  --surface-raised: #ffffff;
  --border: #c7cbd1;
  --link: #0757a6;
  --focus: #0b57d0;
  --muted: #5f6368;
}

[data-theme="dark"] {
  color-scheme: dark;
  --page-bg: #171717;
  --page-text: #f2f2f2;
  --surface: #292929;
  --surface-raised: #202124;
  --border: #5f6368;
  --link: #8ab4f8;
  --focus: #a8c7fa;
  --muted: #bdc1c6;
}

These declarations repeat the tokens deliberately: they make the pinned value independent of the media query. In a larger design system, generate the token sets from one source to avoid drift.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Initialize before first paint

A saved preference that is applied only after deferred application code runs can cause a flash of the wrong theme. Use a small non-deferred script in the head:

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

Do not treat arbitrary storage values as CSS. The allow-list above prevents an unexpected value from becoming an attribute.

Toggle and persistence code

const root = document.documentElement;
const button = document.getElementById('theme-toggle');

function updateButton() {
  const pinned = root.dataset.theme;
  button.setAttribute('aria-pressed', pinned === 'dark' ? 'true' : 'false');
  button.textContent = pinned === 'dark' ? 'Use light mode' : 'Use dark mode';
}

button.addEventListener('click', () => {
  const next = root.dataset.theme === 'dark' ? 'light' : 'dark';
  root.dataset.theme = next;
  localStorage.setItem('theme', next);
  updateButton();
});

updateButton();

If you provide a “System” action, remove the attribute and storage key rather than saving a third CSS value:

function useSystemTheme() {
  root.removeAttribute('data-theme');
  localStorage.removeItem('theme');
  updateButton();
}

With no attribute, the @media rule becomes active again and later operating-system changes are followed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

5. Consider light-dark() when your support policy allows it

CSS can choose between two colors with light-dark() when the element’s color-scheme is active:

:root {
  color-scheme: light dark;
  --page-bg: light-dark(#fff, #171717);
  --page-text: light-dark(#202124, #f2f2f2);
}

Retain fallback declarations for browsers that do not support the function, and verify how your build pipeline handles it. Media queries plus custom properties remain the clearest broadly compatible foundation.

6. Test both schemes instead of trusting defaults

Emulate the preference

In Microsoft Edge DevTools, open the Command Menu or the Rendering tool and set the emulated prefers-color-scheme value to Light and Dark. Chromium-based browsers expose an equivalent rendering emulation. Test a fresh profile as well as a profile with a saved override.

Inspect interaction and content states

  • Read body text, headings, links, visited links, metadata and placeholder text.
  • Check buttons, inputs, selects, checkboxes, dialogs, menus, tooltips and validation messages.
  • Verify borders, separators, shadows and focus indicators remain visible.
  • Inspect images, SVGs, charts, syntax-highlighted code and third-party embeds; they may contain their own fixed colors.
  • Check text over gradients, hero images and translucent surfaces in both schemes.
  • Change the operating-system setting with the page open and confirm that an unpinned page follows it.
  • Pin Light or Dark, change the operating-system setting, reload, and confirm the pin remains.

Browser defaults mixed with author-specified colors cannot guarantee a particular contrast level. The CSS Color Adjustment specification specifically cautions that explicit foreground and background pairs may be necessary. Treat night mode as a preference, not as proof that a site is accessible; assess contrast and keyboard interaction separately.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

7. Framework and component considerations

Tailwind CSS defaults its dark variant to the prefers-color-scheme media feature and can be configured for manual switching with stored theme state. The utility classes do not change the browser APIs: you still need a clear precedence model and a consistent token strategy. For component libraries, expose semantic variables (for example, --surface) rather than hard-coding a separate color in every component.

8. Troubleshooting common failures

Dark mode never appears

Confirm that the media query is exactly @media (prefers-color-scheme: dark), that the stylesheet loads, and that a later rule is not overriding your variables. Inspect a component’s computed styles to find the winning declaration.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Native controls stay light

Ensure both the head meta element and color-scheme: light dark are present. If a pinned state is active, set color-scheme: light or dark on that state so controls follow the pin.

A flash occurs on reload

Move the meta element and the tiny storage-reading script into the head. Do not defer the script that applies a saved attribute. Keep it small and avoid network requests during initialization.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The toggle resets

Check that the code writes and reads the same localStorage key and that the page is not running in a storage-restricted context. Handle storage exceptions if your application must work when storage is blocked.

System changes are ignored

Remove the saved attribute to return to system mode. If your UI mirrors matchMedia in JavaScript, register the change listener; a one-time matches read cannot observe later changes.

Some widgets remain bright

Find fixed colors in component CSS, inline styles, SVG attributes or an embedded frame. Replace them with tokens where you control the source. Cross-origin frames must provide their own theme support.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

9. Capture both versions without setting up a browser

When you need screenshots of the finished light and dark pages for documentation or regression review, ScreenshotNeo can render a URL through one API request. It accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Or skip the browser setup

Use the documented endpoint and options at ScreenshotNeo’s API documentation. This cURL request saves a WebP image:

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

For automation, the same request in Python is:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. Features include full-page and selector captures, device presets, custom viewport and retina scale, PDF controls, custom CSS or JavaScript, clicks, waits, request blocking, headers, cookies, user agents, timezone and geolocation, transparent backgrounds, resizing, chosen-TTL caching, signed image links, asynchronous webhooks, bulk capture of up to 100 URLs per call, a usage API and an OpenAPI specification. Its parameter names are compatible with those used by other screenshot APIs.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try it.

10. Practical performance and maintenance notes

  • CSS custom properties add negligible work compared with loading images, fonts and scripts; keep the token set centralized rather than duplicating large theme stylesheets.
  • Apply the saved attribute before first paint to avoid a visible transition. If you animate colors, respect prefers-reduced-motion and avoid animating large surfaces unnecessarily.
  • Do not rely on dark mode to reduce image or video bandwidth. It changes colors, not resource size.
  • Document which state wins: saved Light or Dark, otherwise system preference. This prevents future components from implementing conflicting logic.
  • When adding a new component, require light and dark tokens plus focus, disabled and error states in its review checklist.

Frequently Asked Questions

Does color-scheme automatically darken my entire website?

No. It changes browser-managed UI and tells the browser which schemes are supported. Your authored backgrounds, text and components still need CSS tokens or theme rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should a saved choice override a later operating-system change?

Yes. An explicit user choice should remain pinned until the user selects system mode or another theme.

Is dark mode by itself an accessibility feature?

No. It is a preference. Check contrast, focus visibility, controls and other interaction states independently in both palettes.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.