cssmedia-queriesdarkmode

How to detect if the OS is in dark mode via CSS?


Is there a way to detect if the user's system is in Dark Mode via the browser?

We would like to change our site's design to be dark-mode friendly based on the current operating mode.


Solution

  • The new standard is registered on W3C in Media Queries Level 5.

    In case user preference is light:

    /* Light mode */
    @media (prefers-color-scheme: light) {
        body {
            background-color: white;
            color: black;
        }
    }
    

    In case user preference is dark:

    /* Dark mode */
    @media (prefers-color-scheme: dark) {
        body {
            background-color: black;
            color: white;
        }
    }
    

    There is also the option no-preference in case a user has no preference. But I recommend you just to use normal CSS in that case and cascade your CSS correctly.