👩💻/CSS, SCSS
SCSS 활용 팁 16. SCSS를 활용한 다크모드 만들기
Purpleo
2025. 2. 6. 21:23
다양한 사용 환경을 고려하고 사용자의 취향에 맞춘 서비스를 제공하기 위해 기본 테마 외에도 다크버전을 제공하는 경우를 자주 보게 됩니다. 이번에는 SCSS의 기능과 Javascript를 활용하여 다크모드를 만드는 방법을 알아보려고 합니다.
HTML 작성
모드를 변경할 HTML코드를 작성합니다. #theme-toggle 버튼을 누르면 페이지가 다크모드로 변경되게 작업하려 합니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SCSS 다크 모드</title>
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<button id="theme-toggle" class="primary">🌚 다크 모드</button>
<script src="script.js"></script>
</body>
</html>
SCSS 변수 설정
_variables.scss파일을 생성하고 여기에 기본 라이트 모드와 다크 모드의 주요 색상을 변수로 지정합니다. 이때 map을 사용하면 가독성 향상에 좋고 사용도 편해집니다.
$light-mode: (
bg: #ffffff,
text: #333333,
primary: #007bff
);
$dark-mode: (
bg: #121212,
text: #ffffff,
primary: #bb86fc
);
Mixin 생성
_theme.scss파일을 생성하고 각 테마의 스타일을 적용하는 믹스인을 작성합니다.
@mixin theme($theme) {
background-color: map-get($theme, bg);
color: map-get($theme, text);
}
@mixin theme-primary($theme) {
background-color: map-get($theme, primary);
color: #ffffff;
}
스타일 적용
이제 style.scss에 _variables.scss와 _theme.scss를 임포트하고, 스타일 코드를 작성합니다. data-theme="dark"속성을 body 태그에 추가하여 다크모드로 변경하는 방식을 사용하겠습니다.
@import "variables";
@import "theme";
body {
@include theme($light-mode); // 기본값은 라이트 모드
transition: background-color 0.3s, color 0.3s;
&[data-theme="dark"] {
@include theme($dark-mode);
}
}
button {
padding: 10px 20px;
border: none;
cursor: pointer;
border-radius: 5px;
&.primary {
@include theme-primary($light-mode);
body[data-theme="dark"] & {
@include theme-primary($dark-mode);
}
}
}
JavaScript로 다크모드 전환
이제 버튼을 누르면 다크모드로 전환되는 효과를 구현하기 위해 JavaScript를 작성합니다. script.js 파일에 다음과 같이 코드를 쓰겠습니다.
const toggleTheme = () => {
const body = document.body;
const isDark = body.getAttribute("data-theme") === "dark";
if (isDark) {
body.setAttribute("data-theme", "light");
localStorage.setItem("theme", "light");
} else {
body.setAttribute("data-theme", "dark");
localStorage.setItem("theme", "dark");
}
};
// 저장된 테마 적용
document.addEventListener("DOMContentLoaded", () => {
const savedTheme = localStorage.getItem("theme") || "light";
document.body.setAttribute("data-theme", savedTheme);
});
// 버튼 클릭 시 다크 모드 전환
document.getElementById("theme-toggle").addEventListener("click", toggleTheme);
#theme-toggle 버튼을 클릭하면 body에 data-theme="dark"속성이 토글되게 하였고, localStorage를 이용하여 설정을 저장해 주었습니다. localStorage를 사용하면 브라우저가 사용자의 설정을 기억하여 새로고침을 하거나 창을 껐다 켜도 이전 설정이 유지됩니다.