How to detect if the OS is in a dark or light mode in browsers?

Sometimes, you want to apply styles for a page opened in Chrome/Firefox and Safari on OSX Dark mode.

OSX provides two themes to indicate light and dark modes. This theme customization provides in Windows also.

  • light: It indicates the light colors of an OS
  • dark: It uses dark colors of an underline OS

How to detect OS Dark light mode in CSS with examples?

CSS provides media queries to detect in Chrome and Firefox. prefers-color-scheme is a CSS media query to detect dark or light colors.

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

As per mozilla🔗, It supports all popular browsers.

For webkit and safari browsers, you can use the prefers-dark-interface media query.

@media (prefers-dark-interface) {
    background: white;
}

javascript to detect dark or light mode theme

[matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in Window object used to return MediaQuery list object that returns matched DOM matches with media query string object Here is an example to check a dark theme for Operating System

if (
  window.matchMedia &&
  window.matchMedia("(prefers-color-scheme: dark)").matches
) {
  console.log("apply styles for OS Dark theme  ");
}

Here is an example to check a dark theme for Operating System

if (
  window.matchMedia &&
  window.matchMedia("(prefers-color-scheme: light)").matches
) {
  console.log("apply styles for OS Light theme  ");
}

Conclusion

To summarize, This tutorial explains how to detect OS dark or light themes and apply styles or logic with CSS and javascript.