1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
게시판

09 / 14

JS 다크모드

velog 헤더의 달 버튼. 누르면 어두워지고, 다시 누르면 밝아져요. HTML에 버튼, CSS에 어두운 색, JS에 "눌렀을 때" 세 가지가 필요해요.

templates/index.html의 <header>에 버튼을 넣고, </body> 바로 위에서 JS 파일을 불러와요.

templates/index.html
  <header>
    <a href="/">crack.log</a>
    <button id="theme">☾</button>
  </header>
templates/index.html
  </main>
  <script src="/static/script.js"></script>
</body>

id="theme"는 class와 비슷한 이름표인데, 페이지에 딱 하나만 있을 때 써요. JS에서 찾기 좋아요.

static/style.css 맨 아래에 어두운 색 세트와 버튼 모양을 추가해요.

static/style.css
.dark {
  --bg: #121212;
  --panel: #1e1e1e;
  --text: #ececec;
  --muted: #a0a0a0;
  --line: #2a2a2a;
}

#theme {
  font-size: 20px;
  background: none;
  border: none;
  color: var(--text);
  cursor: pointer;
}

<body>에 class="dark"가 붙으면 변수 값이 통째로 바뀌어요. 7단계에서 변수로 모아 둔 이유예요. #theme은 id로 고르는 선택자.

이제 static/script.js. 버튼을 누르면 body에 dark를 붙였다 뗐다 해요.

static/script.js
const button = document.getElementById("theme");

button.addEventListener("click", () => {
  document.body.classList.toggle("dark");
  button.textContent = document.body.classList.contains("dark") ? "☀" : "☾";
});
  • document.getElementById("theme") HTML에서 id="theme"인 것을 찾아요.
  • addEventListener("click", ...) 클릭되면 뒤의 함수를 실행해요.
  • classList.toggle("dark") 있으면 빼고 없으면 붙여요.
  • 마지막 줄은 버튼 글자를 해와 달로 바꿔요. 조건 ? 참일때 : 거짓일때.

실행하고 달을 눌러 보세요.

보너스

새로고침하면 다시 밝아지죠. 브라우저에 기억시켜요. script.js를 이걸로 바꾸세요.

static/script.js
const button = document.getElementById("theme");

function apply(dark) {
  document.body.classList.toggle("dark", dark);
  button.textContent = dark ? "☀" : "☾";
}

apply(localStorage.getItem("theme") === "dark");

button.addEventListener("click", () => {
  const dark = !document.body.classList.contains("dark");
  localStorage.setItem("theme", dark ? "dark" : "light");
  apply(dark);
});

localStorage는 브라우저 안의 작은 저장소예요. 서버와 상관없이 내 브라우저에만 남아요.

이 단계 전체 코드
app.py
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")


@app.get("/", response_class=HTMLResponse)
def home(request: Request):
    return templates.TemplateResponse(request, "index.html")
templates/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <title>crack.log</title>
  <link rel="stylesheet" href="/static/style.css">
</head>
<body>
  <header>
    <a href="/">crack.log</a>
    <button id="theme">☾</button>
  </header>
  <main>
    <h1>내 블로그</h1>
    <div class="cards">
      <article class="card">
        <a href="/posts/1">
          <img class="thumb" src="/static/thumb1.svg" alt="">
          <div class="body">
            <h2>FastAPI 첫 서버 띄우기</h2>
            <p>uvicorn 한 줄이면 끝. 흰 화면에 Hello World가 뜨는 순간부터 시작.</p>
            <span class="date">2026년 10월 10일</span>
          </div>
        </a>
        <div class="foot">
          <span>by <b>sfadfe</b></span>
          <span>♥ 518</span>
        </div>
      </article>
      <article class="card">
        <a href="/posts/2">
          <img class="thumb" src="/static/thumb2.svg" alt="">
          <div class="body">
            <h2>Jinja2로 HTML 분리하기</h2>
            <p>app.py 안에 HTML을 문자열로 두면 금방 지저분해진다. templates 폴더로 꺼내자.</p>
            <span class="date">2026년 10월 11일</span>
          </div>
        </a>
        <div class="foot">
          <span>by <b>aa_100</b></span>
          <span>♥ 523</span>
        </div>
      </article>
      <article class="card">
        <a href="/posts/3">
          <img class="thumb" src="/static/thumb3.svg" alt="">
          <div class="body">
            <h2>fetch로 DELETE 보내기</h2>
            <p>버튼 하나에 fetch 한 줄. 서버는 리스트에서 글을 빼고 200을 돌려준다.</p>
            <span class="date">2026년 10월 12일</span>
          </div>
        </a>
        <div class="foot">
          <span>by <b>nosmeri</b></span>
          <span>♥ 9</span>
        </div>
      </article>
    </div>
  </main>
  <script src="/static/script.js"></script>
</body>
</html>
static/style.css
:root {
  --bg: #f8f9fa;
  --panel: #ffffff;
  --text: #212529;
  --muted: #868e96;
  --line: #e9ecef;
  --mint: #12b886;
}

* { box-sizing: border-box; }

body {
  margin: 0;
  font-family: -apple-system, "Segoe UI", "Noto Sans KR", "Malgun Gothic", sans-serif;
  background: var(--bg);
  color: var(--text);
}

header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 32px;
  background: var(--panel);
  border-bottom: 1px solid var(--line);
}

header a {
  font-size: 22px;
  font-weight: 800;
  color: var(--mint);
  text-decoration: none;
}

main {
  max-width: 1000px;
  margin: 0 auto;
  padding: 32px;
}

h1 { font-size: 22px; }

.card {
  background: var(--panel);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.card a { color: inherit; text-decoration: none; }
.card .thumb { display: block; width: 100%; height: 160px; object-fit: cover; }
.card .body { padding: 16px; }
.card h2 { margin: 0 0 8px; font-size: 16px; }
.card p { margin: 0 0 12px; font-size: 14px; line-height: 1.5; color: var(--muted); }
.card .date { font-size: 12px; color: var(--muted); }

.card .foot {
  display: flex;
  justify-content: space-between;
  padding: 10px 16px;
  border-top: 1px solid var(--line);
  font-size: 12px;
  color: var(--muted);
}

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 24px;
}

.card {
  transition: transform 0.25s, box-shadow 0.25s;
}

.card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

.dark {
  --bg: #121212;
  --panel: #1e1e1e;
  --text: #ececec;
  --muted: #a0a0a0;
  --line: #2a2a2a;
}

#theme {
  font-size: 20px;
  background: none;
  border: none;
  color: var(--text);
  cursor: pointer;
}
static/script.js
const button = document.getElementById("theme");

function apply(dark) {
  document.body.classList.toggle("dark", dark);
  button.textContent = dark ? "☀" : "☾";
}

apply(localStorage.getItem("theme") === "dark");

button.addEventListener("click", () => {
  const dark = !document.body.classList.contains("dark");
  localStorage.setItem("theme", dark ? "dark" : "light");
  apply(dark);
});
준비
localhost:8000 ↗