DEV Community

Rafi
Rafi

Posted on

Apply dark theme to your site using prefers-color-scheme

I recently noticed tweet by v8 team that said they have introduced dark theme for v8.dev based on users operating system set theme. I has surprised by it so I did a little digging to see how it works. I did find an awesome css media query called prefers-color-scheme which is surprisingly easy to use.

To apply dark theme to your website if your os set to dark you can use the media query

@media (prefers-color-scheme: dark) {
  body {
    background-color: #282828;
    color: #f3f3f3;
  }
}

Enter fullscreen mode Exit fullscreen mode

Similarly for light theme you could use the media query

@media (prefers-color-scheme: light) {
  body {
    background-color: #fff;
    color: #282828;
  }
}
Enter fullscreen mode Exit fullscreen mode

Here is a sample demo of this https://rafi993.github.io/prefered-color-theme/

try switching your OS dark and light color theme to see this.

Alt Text

Alt Text

Top comments (0)