CSS에서도 변수를 선언하고 이를 사용할 수 있다.
변수를 선언하여 값을 사용하면, 추후 스타일의 변화가 있을 때 손쉽게 변경할 수 있다.
반복적으로 사용되는 색상이나 값을 저장하여 재사용함으로써, CSS를 더 효율적으로 사용해보자.
일단 CSS에서 변수를 선언하는 방법은 다음과 같다.
.test {
--primary-color: red;
}
p {
color: var(--primary-color);
}
위와 같이 --를 붙인 속성의 이름은 var()을 통해서 다른 곳에서도 사용될 수 있다.
다만, 선언된 사용자 지정 속성은 해당 태그와 그 하위의 요소에서만 유효하다.
<div>
<h1>hello</h1>
<div class="test">
<h2>Good</h2>
<p>testing</p>
</div>
<p>have a nice day</p>
</div>
위의 HTML에서 test라는 클래스 이름을 지니는 div 하위에 존재하는 p 태그와 그 바깥의 p 태그가 있다.
위에서 변수 --primary-color은 test라는 클래스 이름을 지니는 div와 그 하위 요소에서만 유효하므로, 바깥의 p태그에는 스타일이 적용되지 않는다.
그렇다면, 이 글의 제목처럼 전역 변수처럼 사용자 지정 속성을 쓸 땐 어떻게 해야할까?
정답은 :root이다.
:root 의사 클래스(Pseudo classes)는 문서트리의 root요소를 선택한다. (이는 마치 html 태그를 선택하는 것과 유사하다)
때문이 :root에 선언된 사용자 지정 속성은 문서 어디서도 접근할 수 있게 되는 것이다. (말 그대로 root에 존재하기 때문이다)
:root {
--primary-color: red;
}
p {
color: var(--primary-color);
}
위와같이 .test에서 :root로 변경된 css가 적용되면, 모든 p태그에 스타일이 적용됨을 확인할 수 있다.
전역변수를 사용하여 다크모드를 구현할 수도 있다.
속성선택자를 사용하여 기존의 사용자 정의 속성의 값을 덮어씌운다.
:root {
--primary-color: red;
}
:root[theme="dark"] {
--primary-color: blue;
}
p, h1, h2 {
color: var(--primary-color);
}
html 태그의 theme 속성값이 만약 "dark"가 된다면, 텍스트의 색깔은 red가 아닌 blue가 된다.
<html theme="dark">
<div>
<h1>hello</h1>
<div class="test">
<h2>Good</h2>
<p>testing</p>
</div>
<p>have a nice day</p>
</div>
</html>
위의 HTML에서 텍스트의 색상은 파란색이다.
자바스크립트를 통해서 이를 조작할 수 있고, 더 나아가 다크모드 토글버튼도 만들 수 있을 것이다.
const root = document.querySelector('html');
root.setAttribute("theme", "light");
html 태그의 theme 속성의 값을 light로 수정한다.
텍스트의 색상은 붉은색이 된다.
https://developer.mozilla.org/en-US/docs/Web/CSS/--*
Custom properties (--*): CSS variables - CSS: Cascading Style Sheets | MDN
Property names that are prefixed with --, like --example-name, represent custom properties that contain a value that can be used in other declarations using the var() function.
developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
Using CSS custom properties (variables) - CSS: Cascading Style Sheets | MDN
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;)
developer.mozilla.org
https://developer.mozilla.org/ko/docs/Web/CSS/:root
:root - CSS: Cascading Style Sheets | MDN
CSS :root 의사 클래스는 문서 트리의 루트 요소를 선택합니다 HTML의 루트 요소는 <html> 요소이므로, :root의 명시도가 더 높다는 점을 제외하면 html 선택자와 똑같습니다.
developer.mozilla.org
'기타' 카테고리의 다른 글
Nginx를 사용하면 어떤 장점이 있을까? (express.js & React.js) (0) | 2023.07.21 |
---|---|
비트코인 지갑 주소에 대해서 (p2pkh, p2sh, p2wpkh, p2wsh) (0) | 2023.07.19 |
이미지 최적화하기 (img 태그 속성 알아보기) (0) | 2023.06.30 |
URI와 URL (0) | 2023.06.26 |
canvas 태그 사용하기 (0) | 2023.06.23 |