JS Tip of the Day: Detecting Dark Mode

Detecting Dark Mode
Level: Intermediate

Modern OSes now allow users to specify a dark mode for their system’s UI. This can be detected using a media query in CSS allowing site authors to also present their site in a dark mode.

@media (prefers-color-scheme: dark) {
  /* add styles for dark mode users */
}

Using matchMedia, dark mode can also be detected in JavaScript using the same query used in the CSS.

let darkModeQuery = matchMedia('(prefers-color-scheme: dark)');
if (darkModeQuery.matches) {
    // user is using dark mode
}

More info: