본문 바로가기

Dev/CSS

다크 모드(Dark mode) 적용 방법! (CSS 미디어 쿼리 prefers-color-scheme)

반응형

다크 모드(Dark mode) 작업은 처음이라 기록, 수정하며 두고두고 볼 예정이다.

 

우선, 다크 모드는 2018년에 macOS Mojave에 처음 소개되었고, 현재는 Windows 10, 안드로이드, ios를 비롯하여 많은 운영 체제에서 지원하고 있다.

이에 따라 점점 많은 애플리케이션과 웹사이트가 운영 체제의 다크 모드에서 어울리는 어두운 계열의 스타일을 추가하고 있는 추세이기 때문에 사용자가 다크 모드로 설정 했을 때 보여지는 프론트 단을 어떻게 설정하는지 알아보려 한다.

 

우리는 항상 시간이 없으니 바로 본론부터 들어가자!

 

prefers-color-scheme 미디어 쿼리

@media (prefers-color-scheme: light) {
  /* 라이트 모드에 적용될 css 정의 */
}
@media (prefers-color-scheme: dark) {
  /* 다크 모드에 적용될 css 정의 */
}

간단하다! 반응형 미디어 쿼리와 같은 방식이다.

prefers-color-scheme를 통해서 light, dark mode를 실시간으로 감지해 상황에 맞는 스타일을 보여주는 것이다!

 

기본적으로 html, css 코드를 작성할 때, 대부분 light mode에서 작업하니

dark 미디어쿼리만 추가해 다크 모드에서 보여질 색상만 수정하면 대부분의 작업이 쉽게 끝날 것이라고 예상된다!

 

 

이해가 안될 수 있다! 그럼 다음 코드를 살펴보자!

See the Pen css-prefers-color-scheme-3 by Dale Seo (@daleseo) on CodePen.

 

 

본인의 테마를 라이트 모드, 다크 모드로 변경하며 테스트 해보면 테마에 맞게 Result가 변하는 것을 볼 수 있다! 오오..

테마 변경하는 법은 다른 분들이 자세하게 설명했으니 패스~

 

CSS Variables 적용

웹 사이트의 규모가 커진다면 다크 모드를 지원하기 위해 일일이 모든 태그나 클래스에 적용해야 하기 때문에

작업하는데 있어 어려움이 커지는 것은 당연하다..

 

그래서 규모가 있는 웹 사이트에서는 CSS 변수(CSS Variables, CSS custom properties)를 이용해

좀 더 효과적으로 다크 모드 스타일을 한다.

 

아래의 코드를 확인해보자!

:root {
  --background: #fff;
  --text: #363636;
  --heading-text: #000;
  --anchor-text: #0076d1;
  --code-background: #efefef;
  --code-text: #000;
}

@media (prefers-color-scheme: dark) {
  :root {
    --background: #202b38;
    --text: #dbdbdb;
    --heading-text: #fff;
    --anchor-text: #0076d1;
    --code-background: #161f27;
    --code-text: #ffbe85;
  }
}

body {
  background: var(--background);
  line-height: 1.6;
  max-width: 600px;
  margin: 0 auto;
}

h1,
h2,
h3 {
  color: var(--heading-text);
}

p,
dl {
  color: var(--text);
}

a {
  color: var(--anchor-text);
  text-decoration: none;
}

code {
  color: var(--code-text);
  background: var(--code-background);
  border-radius: 6px;
  padding: 2.5px 5px;
}

CSS 일반 속성을 건드리지 않고, CSS 변수만 미디어쿼리를 사용해 변경하기 때문에

훨씬 간단하게 다크 모드 스타일을 할 수 있고 유지보수 또한 쉬워진다!

 

더 자세한 사항은 갓갓 MDN을 참고해보록 하자!

https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme

 

prefers-color-scheme - CSS: Cascading Style Sheets | MDN

The prefers-color-scheme CSS media feature is used to detect if the user has requested a light or dark color theme.

developer.mozilla.org

 

 

 

참고

https://www.daleseo.com/css-prefers-color-scheme/

 

CSS 미디어 쿼리 prefers-color-scheme (다크 모드)

Engineering Blog by Dale Seo

www.daleseo.com

 

반응형