Menu
Coddy logo textTech

다크/라이트 테마

Coddy HTML 여정의 JavaScript in Action 섹션에 포함된 레슨 — 27개 중 16번째.

다크/라이트 테마 토글을 구현하는 것은 현대적인 웹사이트에서 흔한 기능입니다. JavaScript를 사용하여 간단한 테마 전환기를 만드는 방법을 배워봅시다.

먼저, 테마를 전환할 버튼을 만듭니다:

<button id="themeToggle">Theme Toggle</button>

다음으로, 라이트 테마와 다크 테마를 위한 기본적인 CSS를 추가해 보겠습니다:

<style>
  :root {
    --background-color: #ffffff;
    --text-color: #333333;
  }
  
  body {
    background-color: var(--background-color);
    color: var(--text-color);
    transition: background-color 0.3s, color 0.3s;
  }
  
  .dark-theme {
    --background-color: #222222;
    --text-color: #f5f5f5;
  }
</style>

이제 테마를 전환하는 JavaScript를 추가해 보겠습니다:


const themeToggle = document.getElementById('themeToggle');
  
themeToggle.addEventListener('click', function() {
  document.body.classList.toggle('dark-theme');
});

버튼을 클릭하면 body 요소에서 'dark-theme' 클래스를 토글합니다.

challenge icon

챌린지

쉬움

버튼의 클릭 이벤트 리스너 내부에서, body 엘리먼트에 "dark-mode" 클래스를 토글하는 코드를 추가하세요.

직접 해보기

<!DOCTYPE html>
<html>
<head>
  <title>Dark/light themes</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <header>
    <h1>Hygge ✨</h1>
    <button id="themeToggle" class="toggle-btn">Toggle Theme</button>
  </header>

  <main>
    <section class="intro">
      <img src="https://images.unsplash.com/photo-1519710164239-da123dc03ef4?auto=format&fit=crop&w=1350&q=80" alt="Cozy hygge scene" class="hero-img">
      <p>
        <strong>Hygge</strong> is a Danish concept that embodies coziness, comfort, and a sense of well-being.  
        It’s about enjoying life’s simple pleasures — candles, warm drinks, good company, and soft blankets.
      </p>
    </section>

    <section class="philosophy">
      <h2>The Philosophy</h2>
      <p>
        Hygge is less about things and more about atmosphere and feelings.  
        It’s creating moments of calm, warmth, and togetherness — a way to nurture happiness in everyday life.
      </p>
    </section>

    <section class="origin">
      <h2>Where It Comes From</h2>
      <p>
        Originating from Denmark, hygge reflects the Danish culture’s deep appreciation for balance, comfort,  
        and community. It’s often credited as one of the reasons why Denmark consistently ranks among the  
        happiest countries in the world.
      </p>
    </section>
  </main>

  <footer>
    <p>☕ Embrace hygge in your daily life.</p>
  </footer>

  <script src="script.js"></script>
</body>
</html>
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

JavaScript in Action의 모든 레슨