Dark Mode: Theme Them All

Dark mode is so in right now that even websites are joining in on the fun. Let's look at how we could leverage the new CSS media query.

10th Dec. 2019

A lot of the mobile and desktop operating systems now support dark mode natively and the browser vendors have started to implement the prefers-color-scheme media query.

As of this writing, this feature is tagged as experimental and could possibly change in the future. However, that does not mean we could not play with it!

prefers-color-scheme Media Query

There are three possible values you could use with the prefers-color-scheme media query.

  1. no-preference

    Indicates that the user has made no preference known to the system.

  2. light

    Indicates that user has expressed the preference for a page that has a light theme (dark text on light background).

  3. dark

    Indicates that user has expressed the preference for a page that has a dark theme (light text on dark background).

You can read more about the draft here.

Show Me The Code!

Take the extremely simple example SCSS below:

// dark-theme.scss
$dark-bg: #2f3640;

@media (prefers-color-scheme: ‘dark’) {
  body {
    background-color: $dark-bg;
  }
}
// styles.scss
$light-bg: #f5f6fa;

body {
  background-color: $light-bg;
}

@import ’./dark-theme.scss’;

By default and when our media query returns false, our website’s background colour will be set to #f5f6fa. This means we will be covered for when the user’s preferred colour scheme is light or no-preference.

The example above should automatically react to the prefers-color-scheme changes.

As you can see from the video, the theme changes when we switch between the light and dark theme :party_popper:.