Dark Mode

#programming #random 2020-05-18

I have added a dark mode to my website.

Dark Mode

Initially, I only based it on the CSS Media Query prefers-color-scheme, which requires no JavaScript to run. However, I decided I want to have a toggle for switching between the two modes. This necessitates a tiny bit of JavaScript. The un-minified source can be viewed at the GoogleChromeLabs GitHub page. The minified source was downloaded from an unpkg cdn url. The toggle button code is © 2019 Google LLC. Licensed under the Apache License, Version 2.0.

In my header.html template, in the navigation bar, I have the following:

<header>
  <nav id="navigation">
    <a id="header-home-link" href="/">walther.guru</a>
    <a href="/blog/">blog</a>
    <a href="/tags/">tags</a>
    <!-- Completely optional dark mode toggle -->
    <dark-mode-toggle
      id="dark-mode-toggle-1"
      appearance="switch"
    ></dark-mode-toggle>
  </nav>
  <script type="module" src="/dark-mode-toggle.mjs"></script>
  <script type="text/javascript">
    const toggle = document.querySelector("dark-mode-toggle");
    document.addEventListener("colorschemechange", (e) => {
      document.documentElement.classList.toggle("dark", toggle.mode === "dark");
      console.log(`Color scheme changed to ${e.detail.colorScheme}.`);
    });
  </script>
</header>

My style.scss file (at the tame of this writing) has the following new rules:

header {
  nav {
    display: flex;
  }
  dark-mode-toggle {
    margin-left: auto;
  }
}
/* Dark mode */

.dark {
  body,
  header,
  footer,
  main,
  #container {
    background-color: #111;
  }

  /* All text to white by default */
  * {
    color: white;
  }

  /* Override some of them back for style */
  h1,
  .post_link {
    color: $darkgrey;
  }

  .date,
  .tags a {
    color: $lightestgrey;
  }

  tr {
    border-bottom: 1px solid white;
  }

  th,
  td {
    border-right: 1px solid white;
  }
}