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

Use window.matchMedia('(prefers-color-scheme: dark)').matches to check whether the browser’s effective color-scheme preference currently matches dark. If your page must respond when that preference changes, listen for the returned MediaQueryList’s change event. If you only need to change styles, use CSS instead.

Check the current dark-mode preference

window.matchMedia() evaluates a CSS media query and returns a MediaQueryList. Its matches property is a synchronous boolean: true means the query matches now; false means it does not.

const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

if (prefersDark) {
  document.documentElement.dataset.theme = 'dark';
} else {
  document.documentElement.dataset.theme = 'light';
}

The query is (prefers-color-scheme: dark). The shorter expression window.matchMedia('(prefers-color-scheme: dark)').matches is enough when you only need a one-time decision. The check describes the effective preference for the page’s context—not necessarily a universal reading of a device-wide setting. MDN describes prefers-color-scheme as reflecting a user’s preference for a light or dark scheme.

One important interpretation detail: a non-matching dark query does not prove that someone explicitly chose light mode. The media feature’s light value also applies when no active color-scheme preference has been expressed. In user-facing logic and logs, prefer wording such as “dark preference matches” and “dark preference does not match” over asserting that every other user selected light.

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.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Keep the page in sync when the preference changes

The initial .matches check does not keep running. If the user changes their system or browser preference while the page is open and your application needs to react, register a change listener on the same MediaQueryList. The event’s matches value gives the new status.

const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');

function applyColorScheme(isDark) {
  document.documentElement.dataset.theme = isDark ? 'dark' : 'light';
}

// Set the initial state before waiting for changes.
applyColorScheme(darkModeQuery.matches);

darkModeQuery.addEventListener('change', (event) => {
  applyColorScheme(event.matches);
});

This is the practical pattern for JavaScript-controlled behavior as well as theme selection: initialize from the current value, then update from each change event. For compatibility details and the returned object’s behavior, see MDN’s Window.matchMedia() reference and MediaQueryList change-event reference.

Do not add a listener for a one-time branch. If the listener is attached inside a component that can be destroyed, remove it in that component’s cleanup so the callback does not remain attached after the component is gone.

const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleSchemeChange = (event) => {
  applyColorScheme(event.matches);
};

applyColorScheme(darkModeQuery.matches);
darkModeQuery.addEventListener('change', handleSchemeChange);

// Run when the owning component or page feature is disposed:
darkModeQuery.removeEventListener('change', handleSchemeChange);

Use CSS when the goal is visual styling

If the only result you want is different colors, JavaScript is unnecessary. CSS can respond directly to the same preference, reducing application code and avoiding a separate synchronization step.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
:root {
  color-scheme: light dark;
  --page-bg: #ffffff;
  --page-fg: #202124;
}

@media (prefers-color-scheme: dark) {
  :root {
    --page-bg: #181a1b;
    --page-fg: #f1f3f4;
  }
}

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

Put the site’s actual theme values in the custom properties and reference them throughout the styles. The media query determines which values apply; it does not supply a palette or automatically redesign the page. Keep text, borders, controls, focus indicators, images, and other meaningful elements legible in both schemes.

Use JavaScript when the preference needs to drive application logic—such as selecting a theme class, coordinating a chart or canvas, or updating a component state. If CSS alone can produce the desired appearance, prefer the CSS media query.

Declare supported schemes for browser-controlled UI

When a document supports both light and dark, declare that near the start of its HTML head:

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

The declaration tells the browser which schemes the document supports and gives their preference order. It can let browser-controlled interface elements use an appropriate supported scheme. It does not define your site’s background, foreground, or component colors; your CSS still needs to style those. The details are in MDN’s reference for <meta name="color-scheme">.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

The CSS color-scheme property and the HTML metadata declaration concern supported schemes and browser rendering; the prefers-color-scheme query is the condition used to select styles based on preference. They work together, but they are not interchangeable.

Respect application overrides

Some interfaces let a person choose Light, Dark, or System. In that design, treat the media query as the System setting, not as an instruction that must override an explicit choice. A useful precedence rule is: apply an explicit saved choice when present; otherwise follow matchMedia(). Listen for preference changes only while the active choice is System.

For a simple document with no manual choice, the dataset example above is sufficient. For a full theme selector, keep the choice and the rendered theme as distinct concepts. A saved “dark” selection should remain dark if the operating-system preference later changes; a saved “system” selection should update with the media-query event. This prevents the browser preference from unexpectedly undoing a deliberate in-app selection.

If server-rendered markup also needs a theme before client-side JavaScript runs, plan how the server and client agree on the initial theme. The media query is evaluated in the browser; server code cannot call window.matchMedia() during rendering because window is a browser global. CSS media queries are often the simplest way to avoid waiting for a JavaScript theme assignment for purely visual changes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Understand what the preference means in embedded content

The result is contextual. In particular, embedded SVG and iframe content may use the color scheme of the page that embeds them. Do not assume a nested document’s result is always a separate, direct report of the device setting. The W3C’s Media Queries Level 5 specification describes the preference as reflecting the user’s desire for a light or dark page theme and defines the media feature in its context.

If an embedded component appears to choose a different scheme than expected, check the embedding page and the context in which the SVG or iframe is rendered, rather than assuming the JavaScript expression is broken.

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

Compatibility and testing

MDN’s compatibility summaries mark prefers-color-scheme widely available across browsers since January 2020, Window.matchMedia() since July 2015, and the MediaQueryList change event since September 2020. These are compatibility milestones, not a guarantee for every in-app browser, webview, or embedded environment. Test the browsers and contexts your application actually supports.

  • Test with the browser or operating-system appearance set to dark and light, and confirm both the initial rendering and any live change.
  • Test an explicit in-app theme setting separately from System mode, if your application has one.
  • Check embedded SVG or iframe behavior in the parent-page context where it will be used.
  • When a design is CSS-only, test its media query without introducing JavaScript just to read the same preference.

The related Sec-CH-Prefers-Color-Scheme client hint and User Preferences API are not needed for the ordinary client-side detection task. For normal page behavior, matchMedia() is the direct browser API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Troubleshoot common dark-mode detection problems

The page always looks light

First check the exact query string, including parentheses and the dark value. Log window.matchMedia('(prefers-color-scheme: dark)').matches in the browser console. If it is false, the effective preference is not matching dark in that context; it does not establish that the user explicitly selected light. If it is true but the page stays light, verify that your code or CSS actually applies dark styles and that another selector is not overriding them.

The page starts correctly but does not update

A one-time read only reports the initial value. Attach a change listener to the MediaQueryList, initialize the interface from .matches, and apply the event’s matches value when it fires. If you have an in-app override, make sure the listener is allowed to update the page only when the active selection is System.

Browser controls do not match the site theme

Declare the schemes the document supports with the color-scheme metadata or CSS property, then style the site itself for those schemes. The declaration can inform browser-controlled UI, but it does not create the site’s color palette.

An iframe or SVG reports an unexpected result

Check its embedding context. Embedded content may use the parent page’s effective scheme, so its query result need not correspond to an independent device-wide setting.

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

A listener keeps running after a component disappears

Store the handler function and pass that same function to removeEventListener('change', handler) during component cleanup. Anonymous inline callbacks are harder to remove later because cleanup needs the original callback reference.

Or skip the browser setup

ScreenshotNeo does not detect dark-mode preferences or replace matchMedia(); it captures a rendered web page. If your next step is to inspect or save a page screenshot, ScreenshotNeo offers a one-request screenshot API, with PNG, JPEG, WebP, or PDF output. For example, this cURL request captures Stripe’s page:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo documentation for request options and details. It can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan. Sign up for free and try ScreenshotNeo.

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

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.