Detect dark mode

Read the prefers-color-scheme media feature.

JavaScriptBrowser · DOM Version 1.0.0 · MIT · .md

detect-dark-mode.js
function isDarkMode() { return window.matchMedia?.('(prefers-color-scheme: dark)').matches ?? false; }

Usage

usage.js
// With the system appearance set to dark:
isDarkMode(); // → true

Lines marked → were executed in headless Chromium against the markup above, and each result was compared with the value shown. Lines marked e.g. are illustrative.

Know the limits

  • The preference can change while the page is open: listen for the change event on the MediaQueryList.
  • For styling alone, the CSS media query or light-dark() needs no JavaScript.

The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.

Source & maintenance

Based on Detect dark mode from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

A function instead of a value read once at load. Executed in Chromium with dark mode emulated. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Usage lines executed in headless Chromium against the fixture markup; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.