Preloader
Web development
  • Estimated reading time: 1 Minute

How to detect if the user prefers a light or dark color schema in the browser with JavaScript and CSS

How to detect if the user prefers a light or dark color schema in the browser with JavaScript and CSS

In the recent days, i bought a Mac that had MacOS Mojave installed. Curiously, in some websites that used to have a white background when i visited them on Windows, however in my mac, the website background was dark. This happens because of the preferred color scheme on the Mac, that is dark in my case. I didn't knew that there was a way to detect this on your website, however i want to share with you how to do it either with plain CSS or JavaScript easily.

A. With CSS

The CSS Media Feature prefers-color-scheme allows you to detect in the browser, whether the user prefers a light or dark color theme based on the operative system configuration. The CSS syntax is the following, for example, if the user prefers the dark schema, you should be able to set a dark background with the following CSS:

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

Or a light one:

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

B. With JavaScript

If you prefer to run some JavaScript code according to the preference of the user, you can verify this condition verifying if the browser supports matchMedia and verify if the condition of the color scheme dark matches:

const userPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

const userPrefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;

if(userPrefersDark){
    console.log("User prefers a dark interface");
}

For another developer-friendly shortcut, a structured data generator can create valid Schema.org JSON-LD in the browser without requiring you to write the markup manually.

Happy coding !

Share:
Carlos Delgado

Carlos Delgado

Senior Software Engineer at Corvix. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Our Sponsors

Our blog is proudly supported by industry-leading sponsors.