DEV Community

Cover image for Add Dark Theme to your Website
Amjad Abujamous
Amjad Abujamous

Posted on • Edited on

Add Dark Theme to your Website

Code Pen

https://codepen.io/glorious73/pen/rNRXGex

Introduction

Let's face it, we live in an age where it is a must to give the user the choice between a Light and a Dark theme while using websites and apps. This article is meant to illustrate a clean and reliable way of acheiving just that on the web.

Method

The following is a method that uses the media query which checks if the users prefers dark theme and sets the theme as such. Then it allows the user to switch themes and saves it in local storage for future visits.

  1. Upon application load, check if the user already chose a theme in past visits by reading local storage.
  2. If the user chose one, assign it. If, on the other hand, this is their first visit, check the system theme using window.matchMedia("(prefers-color-scheme: dark)").
  3. Assign the theme to match the system using an introduced attribute to html and then save it in local storage.
  4. Change the colors of the app purely based on the html theme.

The source code below should serve for a good example.

Html

<!DOCTYPE html>
<!--To set the theme for the html element below-->
<html>
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/png" href="/img/logo.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My App</title>
  </head>
  <body>
    <div id="main">
      <h1>This is a dummy text illustrating the use of themes.</h1>
      <div class="entry">
        <h2 class="key">Theme</h2>
        <div class="radios">
          <input type="radio" id="light" name="theme">
          <label class="option-one" for="light">
          Light
          </label>
          <input type="radio" id="dark" name="theme">
          <label class="option-two" for="dark">
          Dark
          </label>
        </div>
      </div>
    </div>
    <script type="module" src="/src/index.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Javascript

Now, in index.js, here is what needs to be done to set the theme.

class Theme {
    constructor() {
        this.selectedTheme = localStorage.getItem("theme"); // 'light' or 'dark'
    }

    static getInstance() {
        if (!this.instance)
            this.instance = new Theme();
        return this.instance;
    }

    setTheme(theme) {
        this.selectedTheme = theme;
        const html         = document.querySelector("html");
        html.setAttribute("theme", theme); // set theme here!!
        localStorage.setItem("theme", theme); // future visits
    }

    getTheme() {
        return this.selectedTheme;
    }
}

function loadTheme() {
  let selectedTheme = Theme.getInstance().getTheme();
  if(!selectedTheme) {
    const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
    selectedTheme = (prefersDarkScheme.matches) ? "dark" : "light";
  }
  Theme.getInstance().setTheme(selectedTheme);
}

loadTheme()
Enter fullscreen mode Exit fullscreen mode

Styles (Css)

Now, the styles in your app should solely depend on variables which change based on the theme attribute of the html element, like so.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

:root {
  --primary-color: #ffffff;
  --secondary-color: #2d5c8a;
  --accent-color: #f2f2f2;
  --text-color: #1b1212;
  --white-color: #ffffff;
  --success-color: #077d0b;
  --error-color: #ff4d00;
  --box-shadow-color: rgba(0,0,0,0.2);

  color-scheme: light dark;
}

html[theme="dark"] {
  --primary-color: #242424;
  --secondary-color: #2d5c8a;
  --accent-color: #1f1f1f;
  --text-color: #ffffff;
  --white-color: #ffffff;
  --success-color: #077d0b;
  --error-color: #ff4d00;
  --box-shadow-color: rgba(212, 212, 212, 0.2);
}

body {
  background-color: var(--primary-color);
  color: var(--text-color);
}
Enter fullscreen mode Exit fullscreen mode

Usage

Finally, all you need is a theme switcher to change the theme while the user is using the app. The following is an example that shows you how one can be done.

<div class="entry">
  <h2 class="key">Theme</h2>
  <div class="radios">
    <input type="radio" id="light" name="theme">
    <label class="option-one" for="light">
     Light
    </label>
    <input type="radio" id="dark" name="theme">
    <label class="option-two" for="dark">
     Dark
    </label>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
.key {
  font-weight: normal;
}

.entry {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 1rem;
}

.radios {
  display: flex;
  align-items: center;
  border: 1px solid var(--text-color);
  border-radius: 0.8rem;
  width: 10rem;
  padding: 0.5rem 0;
  padding: 0;
}

input[type=radio] {
  display: none;
}

input[type="radio" i] {
  margin: 0 !important;
  padding: 0 !important;
}

input[type=radio]+label {
  display: inline-block;
  width: 5rem;
  padding: 0.5rem 0;
  font-size: 1rem;
  text-align: center;
  cursor: pointer;
  background-color: var(--primary-color);
  color: var(--text-color);
  transition: all 0.25s ease;
}

input[type=radio]+label.option-one {
  border-top-left-radius: 0.8rem;
  border-bottom-left-radius: 0.8rem;
}

input[type=radio]+label.option-two {
  border-top-right-radius: 0.8rem;
  border-bottom-right-radius: 0.8rem;
}

input[type=radio]:hover+label {
  font-weight: bold;
}

input[type=radio]:checked+label {
  outline: 0;
  color: var(--primary-color) !important;
  background: var(--secondary-color);
}
Enter fullscreen mode Exit fullscreen mode
const currentTheme = Theme.getInstance().getTheme();
const themes = document.querySelectorAll('input[name="theme"]');
themes.forEach(element => {
  if(element.id == currentTheme)
    element.setAttribute("checked", "checked");
  element.addEventListener("change", async () => await setTheme(element.id));
});

function setTheme(theme) {
 Theme.getInstance().setTheme(theme);
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

We have explored a way of making the user feel comfortable with viewing a web app or a web page using their system's theme of choice and giving them the ability to change it at any time.

Image Credit

https://forms.app/en/blog/benefits-of-dark-mode

Top comments (0)