In this lesson, we use CSS variables with calc and hsl to implement a rudimentary dark mode.

We can do this by adjusting the lightness of our colors based on a binary value and some basic arithmetic.+

 

:root {
  --dark: 1;
  --bg: hsl(190, 50%, calc((80 - (var(--dark, 0) * 60)) * 1%));
  --color: hsl(190, 20%, calc((30 + (var(--dark, 0) * 30)) * 1%));
}

body {
  min-height: 100vh;
  background: var(--bg);
  color: var(--color);
  font-family: sans-serif;
  font-size: 2.5rem;
  transition: background 0.2s, color 0.2s;
}

h1 {
  position: absolute;
  bottom: 1.25rem;
  right: 1.25rem;
  margin: 0;
  user-select: none;
}
document.addEventListener("click", () => {
  document.documentElement.style.setProperty(
    "--dark",
    document.documentElement.style.getPropertyValue("--dark") === "1" ? 0 : 1
  );
});