DEV Community

Garis Space
Garis Space

Posted on

1 1

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)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay