Learn how to automatically define the color schema of your website according to the user preference in the operative system.

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 !


Senior Software Engineer at Software Medico. 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.

Sponsors