Dark Mode: A Media Query

Many apps and websites utilize dark mode; when the device is placed in dark mode, apps and websites follow suit. This is fairly simple to accomplish with modern web browsers.

Note: in this example, the website will follow the device settings. A more advanced approach would allow the user to override the device settings within the web page.

Begin by declaring the colors used for dark mode. The following example uses lightgray text on a dimgray background within body.

(Always begin with dark mode. If a user in dark mode loads a web page that defaults to light mode, their screen may briefly flash the original settings; that defeats the purpose of dark mode.)

Next, add a media query @media (prefers-color-scheme: light). Within the media query, redefine the color and background-color properties for body.

/* Always begin with dark mode to avoid a flash of light when loading in dark mode */

body {
    background-color: dimgray;
    color: lightgray;
}

/* add a media query to switch themes */

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