To enable the dark theme press “d”, to disable the dark theme press “s”. Also, the dark theme could be enabled by your device’s settings.

There is great research that mentions a couple of things in favor of dark mode - Hello darkness, my old friend. Despite the things mentioned in the post, I have a couple of own reasons to add the dark theme:

  • to reduce eye strain
  • I prefer dark mode and I am sure there are lots of people that like dark mode too
  • I use this website to build and present slides, so I often need a dark background

How does it work?

Imagine we have dark-theme.css file that brings “darkness”

/* dark-theme.css */
body {
  background: black !important;
  color: white !important;
}
/* ... */

We can use prefers-color-scheme CSS media feature to apply the CSS when a device’s settings are set in favor of a dark theme:

<link id="js-dark-theme" rel="stylesheet" href="/dark-theme.css" media="(prefers-color-scheme: dark)">
<script src="dark-theme.js"></script>

To provide an ability to enable or disable the dark theme from a website we should add a little JavaScript code. For instance, the following code enables the dark theme:

document.getElementById("js-dark-theme").media = "";

To disable the dark theme we can set the media attribute to the original value:

document.getElementById("js-dark-theme").media = "(prefers-color-scheme: dark)";

Another important issue we should solve is retaining a user’s settings between pages. We can either use Window.sessionStorage or Window.localStorage to achieve this. We can save settings on enabling the dark theme:

window.sessionStorage.setItem("darkTheme", "enable");

and on disabling the dark theme:

window.sessionStorage.setItem("darkTheme", "disable");

Then we should add JavaScript code that executes on every page of the website like:

if (window.sessionStorage.getItem("darkTheme") === "enable") {
  document.getElementById("js-dark-theme").media = "";
} else if (window.sessionStorage.getItem("darkTheme") === "disable") {
  document.getElementById("js-dark-theme").media = "(prefers-color-scheme: dark)";
}

That is it!