← 레벨 2 – 위저드

수업 4/8 ⏱ 30 분

웹사이트를 위한 다크 모드

브라우저를 닫은 후에도 웹사이트가 기억하는 밝은/어두운 테마 전환기야.

작동 방식

다크 모드는 두 부분으로 구성된 주문야.

  1. CSS는 두 번째 “의상”을 준비해. 페이지에 클래스가 있는 경우에만 적용되는 규칙야.dark.
  2. JavaScript는 클릭 시 해당 클래스를 추가하거나 제거해. 그리고 선택한 내용을 브라우저의 메모리에 기록하므로 내일도 적용돼.

보여줄게: CSS의 어두운 의상

이것을 맨 마지막에 추가해.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;
}

다음과 같이 읽어보세요: “언제body수업이 있어요dark, 이러한 규칙이 적용돼.” 클래스가 없으면 이 중 어느 것도 사용되지 않어.

💡
웹사이트에 맞게 색상을 조정해. CSS를 살펴보고 밝은 색상마다 어두운 색상을 찾아보세요. 규칙은 동일하게 유지돼: 어두운 배경 → 밝은 텍스트.

보여줄게: JavaScript의 스위치

헤더에 버튼 추가(내부)<nav>):

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

그리고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 = "🌙";
  }
});

새로운 세 가지:

네 차례 💪

  1. 나만의 어두운 의상을 추가해style.css– 모든 색상(배경, 머리글, 카드, 바닥글, 배지)을 살펴보고 아래에 어두운 버전을 제공해.body.dark.
  2. 모든 페이지의 헤더에 스위치 버튼을 추가하고 코드를 추가해.script.js.
  3. 사용해 보세요. 어두운 모드로 전환하고 브라우저를 닫은 후 웹사이트를 다시 엽니다. 그러면 바로 어두운 모드로 열어.
더욱 완성도 높은 어두운 의상의 예(프로젝트에 맞게 색상 조정)
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;
}
**직접 확인해 보세요:** 🌙을 클릭하면 웹사이트가 어두워지고(아이콘이 ☀️로 변경됨), ☀️를 클릭하면 다시 밝아집니다. 브라우저를 닫았다가 다시 열면 웹사이트가 사용자의 선택을 기억해. 이것은 많은 "성숙한" 웹사이트에는 없는 기능야!

이번 수업에서 배울 점