Simple Dark/Light mode

matoval

matoval

Posted on May 13, 2020

Simple Dark/Light mode

Here is the simplest way I found to add dark mode to a project:
Add a toggle button in your HTML with a checkbox and an onClick calling a JavaScript function

 <label id="toggle">
   <input type="checkbox" onclick="toggleDarkMode(event)">
   <span id="slider"></span>
 </label>
Enter fullscreen mode Exit fullscreen mode

Then add a data-mode to your CSS with your CSS variables set to the dark mode colors

:root {
  font-size: 10px;
  --bg: white;
  --font-color: black;
  --btn-bg: black;
  --btn-color: white;
}

[data-mode="dark"] {
  --bg: black;
  --font-color: white;
  --btn-bg: white;
  --btn-color: black;
}
Enter fullscreen mode Exit fullscreen mode

Now all you have left is to write the JavaScript function to set or remove the data-mode

function toggleDarkMode(event) {
  const isDarkmode = event.target.checked

  if (isDarkmode) {
    document.documentElement.setAttribute('data-mode', 'dark')
  } else {
    document.documentElement.setAttribute('data-mode', '')
  }
}
Enter fullscreen mode Exit fullscreen mode

Then you can add some CSS to make the button look better and add a transition

:root {
  font-size: 10px;
  --bg: white;
  --font-color: black;
  --btn-bg: black;
  --btn-color: white;
}

[data-mode="dark"] {
  --bg: black;
  --font-color: white;
  --btn-bg: white;
  --btn-color: black;
}

body {
  width: 100vw;
  font-size: 2rem;
  background-color: var(--bg);
  color: var(--font-color);
}

#toggle {
  margin-right: 2rem;
  width: 6rem;
  height: 3.4rem;
  border-radius: 3rem;
  background-color: var(--btn-bg);
}

#toggle input {
  opacity: 0;
  width: 0;
  height: 0;
}

#slider {
  position: absolute;
  z-index: 5;
  cursor: pointer;
  height: 2.5rem;
  width: 2.5rem;
  top: 1.23rem;
  right: 1.8rem;
  border-radius: 3rem;
  background-color: var(--btn-color);
  transition: ease-in .2s;
}

#slider.dark {
  right: 4.2rem;
}
Enter fullscreen mode Exit fullscreen mode

Here is the end result:

💖 💪 🙅 🚩
matoval
matoval

Posted on May 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related