Check If User Has Browser Theme Preference Set To Light Or Dark With JavaScript

July 21, 2023 by Andreas Wik

Checking what preferred color scheme the user has set in their browser can be useful for a number of things. Perhaps you have a dark and a light theme set up, and on page load you want to select the user’s preferred theme.

You may want to check my other article out: Switch between dark theme and light theme and light theme with CSS and JavaScript

With JavaScript you can simply check window.matchMedia for what prefers-color-scheme is set to. To check if the preferred color scheme is dark, use it like this

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    // Dark theme
} else {
    // Light theme
}

 

You can also detect it using a CSS media query, like this:

@media (prefers-color-scheme: dark) {
    /* Dark theme styles */
}

@media (prefers-color-scheme: light) {
    /* Light theme styles */
}

 

Have fun!

 

Share this article

Recommended articles