JS & CSS snippet to detect and style if dark mode

Garis Space
Sep 19, 2022

This JavaScript snippet detects if the user is in dark mode. And if so, it returns true.

const isDarkMode = () =>
globalThis.matchMedia?.("(prefers-color-scheme:dark)").matches ?? false;

// Usage
isDarkMode();

The prefers-color-scheme CSS media feature lets you detect if the user's system is set to dark mode or light mode.

@media (prefers-color-scheme: dark) {
body {
background-color: black;
color: white;
}
}

@media (prefers-color-scheme: light) {
body {
background-color: white;
color: black;
}
}

--

--