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");
}

Happy coding !

This could interest you

Become a more social person