← Level 2 – Wizard

Lesson 4 of 8 ⏱ 30 minutes

Dark mode for your website

A light/dark theme switcher that the website remembers even after you close the browser.

How it will work

Dark mode is a spell made of two parts:

  1. CSS prepares a second “costume” – rules that only apply when the page has the class dark.
  2. JavaScript adds or removes that class when clicked. And it writes what you picked into the browser’s memory, so it still applies tomorrow.

Show me: the dark costume in CSS

Add this to the end of style.css:

body.dark {
  background-color: #1c1917;
  color: #f5f0ea;
}

body.dark h1,
body.dark h2 {
  color: #93c5fd;
}

body.dark .card {
  background-color: #292524;
  color: #f5f0ea;
}

Read it like this: “When body has the class dark, these rules apply.” Without the class, none of this is used.

💡

Adjust the colors to fit your website – go through your CSS and come up with a dark sibling for every light color. The rule stays the same: dark background → light text.

Show me: the switch in JavaScript

Add a button to the header (inside <nav>):

<button id="switch">🌙</button>

And in script.js:

const switchButton = document.getElementById("switch");

// When the page loads: remember what the visitor picked last time
if (localStorage.getItem("mode") === "dark") {
  document.body.classList.add("dark");
  switchButton.textContent = "☀️";
}

switchButton.addEventListener("click", () => {
  document.body.classList.toggle("dark");

  if (document.body.classList.contains("dark")) {
    localStorage.setItem("mode", "dark");
    switchButton.textContent = "☀️";
  } else {
    localStorage.setItem("mode", "light");
    switchButton.textContent = "🌙";
  }
});

Three new things:

Your turn 💪

  1. Add a dark costume to your own style.css – go through all your colors (background, header, cards, footer, badges) and give them dark versions under body.dark.
  2. Add a switch button to the header on every page and the code to script.js.
  3. Try it out: switch to dark, close the browser, open the website again – it should open straight into dark mode.
Example of a more complete dark costume (adjust colors to fit your project)
body.dark {
  background-color: #1c1917;
  color: #f5f0ea;
}

body.dark h1,
body.dark h2,
body.dark h3 {
  color: #93c5fd;
}

body.dark header {
  background-color: #0f172a;
}

body.dark .card {
  background-color: #292524;
  color: #f5f0ea;
  box-shadow: none;
}

body.dark footer {
  background-color: #0f172a;
}

body.dark a {
  color: #93c5fd;
}

Check yourself: Clicking 🌙 makes the website go dark (and the icon changes to ☀️), clicking ☀️ makes it light again. After closing and reopening the browser, the website remembers your choice. This is a feature that plenty of “grown-up” websites don’t even have!

What to take away from this lesson