Applying dark mode in CSS

With the introduction of macOS Mojave in 2018, you can select to have system-wide dark mode applied to the UI. Windows 10 also added a similar feature starting with the October 2018 system update.

Creating a colour scheme with CSS custom properties

The easiest way to implement dark mode is using CSS custom properties. Simply define the colour scheme used in your site on the :root selector, and use those in your stylesheets, like so:

:root {
  --color-background: #fff;
  --color-text: #222;
  --color-primary: #af1440;
}

body {
  color: var(--color-text);
  color: var(--color-background);
}

h1, h2, h3, h4, h5, h6, a {
  color: var(--color-primary);
}

Then add a media query to detect when dark mode is preferred, and redefine those colours to a darker theme:

@media (prefers-color-scheme: dark) {
  :root {
    --color-background: #222;
    --color-text: #af1440;
    --color-primary: #af1440;
  }
}

Browser support

The CSS required to support this is currently only implemented on macOS, and is only available in Safari 12.1, and in Firefox 67 (beta as of writing). On systems/browsers without support, it will fallback to using the light colour scheme.