DEV Community

Garis Space
Garis Space

Posted on

JS & CSS snippet to detect and style if dark mode

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();
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)