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.

10 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:.

Similar Posts

Cypress Part I: Getting Started

In this new series, we look at how we could include Cypress as part of our testing strategy for our single page applications.

15 Nov 20195-minute read

Cypress Part II: Configuration

Now that we have added Cypress to our existing SPA, let's have a look at overriding the default configurations.

04 Dec 20192-minute read

Typescript 3.7

The new version of TypeScript has been released and with it comes optional chaining as well as nullish coalescing!

05 Nov 20191-minute read