← Web basics: HTML, CSS and JavaScript

Project: a light/dark toggle

One class on the body switches the whole page's colors.

Start this lesson

Dark mode is easier than it looks. Write normal colors for body, then a second rule, body.dark, with dark colors. Because colors inherit, every element inside follows. JavaScript only has to toggle one class on document.body when the button is clicked. A good toggle also tells everyone its state: update the button text, and set aria-pressed to "true" or "false" so screen readers announce whether dark mode is on.

body { background-color: white; color: #222; }
body.dark { background-color: #1e1e1e; color: #f0f0f0; }

button.addEventListener("click", () => {
  const isDark = document.body.classList.toggle("dark");
  button.textContent = isDark ? "Light mode" : "Dark mode";
  button.setAttribute("aria-pressed", String(isDark));
});

classList.toggle returns true if the class is now on. The ? : ("if ... then ... else" in one line) picks the button text from that.

Browsers can tell you whether the visitor's system is in dark mode with the media query @media (prefers-color-scheme: dark). Many sites use it to choose the starting theme.

Check contrast in both themes. Light gray on dark gray can fail just like gray on white.