Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 정렬
- 빅오
- TypeScript
- textarea autosize
- 블로그만들기
- isNaN
- NextAuth
- aws lightsail
- next.js
- 그리디
- react-query
- typscript
- 슬라이딩윈도우
- JavaScript
- Algorithm
- nestjs
- 라이프사이클
- 스택
- tailwindcss
- js알고리즘
- nextjs
- 큐
- styled-components
- 투포인터
- 알고리즘
- 해쉬
- 버블정렬
- cookie
- react
- never타입
Archives
- Today
- Total
far
[CSS] 다크 모드 적용하기 본문
이번에 vanilla javascript로 간단한 화면을 만들 일이 있어서 다크 모드를 적용해봤다. 처음에는 미디어 쿼리를 이용해 prefers-color-scheme라는 방법으로 적용했는데, 자체적인 컬러모드 적용이 어렵고, 사용자가 다크 모드를 on/off 전환 할 수 없다는 문제가 있어 dataset으로 구현을 해봤다.
base.html
<button id="darkMode">
<i class="gg-dark-mode"></i>
Dark Mode
</button>
HTML에 다크 모드 on/off를 선택하기 위한 버튼을 만든다.
style.css
/* light mode */
body {
height: 100vh;
overflow-x: hidden;
background-color: rgb(255, 255, 255);
}
/* dark mode */
body[data-theme='dark'] {
background-color: #000;
color: #fff;
}
body[data-theme='dark'] .gg-arrows-exchange {
color: #fff;
}
css에 다크 모드를 적용했을 때의 CSS를 만든다.
나는 body에 data-theme='dark'를 추가 시킴으로써 다크 모드를 제어할 것이기 때문에 다크 모드시 적용될 모든 css 선택자 앞에 body[data-theme='dark']를 붙여줬다. 그러면 다크 모드 on이 되었을 때 body[data-theme='dark']가 붙은 CSS들이 일괄적용 된다.
main.js
const darkmode = document.getElementById('darkMode');
darkmode.addEventListener('click', () => {
if (!document.body.hasAttribute('data-theme', 'dark')) {
document.body.setAttribute('data-theme', 'dark');
} else {
document.body.removeAttribute('data-theme', 'dark');
}
});
HTML의 button에 걸어둔 id를 가져와서 클릭시 attribute를 추가/제거 할 수 있도록 toggle을 만들었다.
만약 dateset으로 관리하고 싶지 않다면 setAttribute대신 classList.add/remove를 사용해 class로 관리할 수 있게 만들 수 있다.
'HTML, CSS' 카테고리의 다른 글
[UI] 레이아웃 시프트(Layout Shift)에 대해서 (0) | 2024.08.19 |
---|---|
[CSS] pre태그 텍스트 영역 초과 현상 해결하기 (0) | 2023.04.06 |
[CSS] 캐스케이딩(Cascading)과 상속 (1) | 2023.03.24 |
[TailwindCSS] Tailwind의 커스터마이징 (0) | 2023.03.17 |
[HTML] 시맨틱 태그와 사용하는 이유 (0) | 2023.03.13 |
Comments