Custom Properties
.first-list {
background-color: thistle;
color: whitesmoke;
margin-left: 8px;
--font-size: 32px;
}
.second-list {
background-color: thistle;
color: whitesmoke;
margin-left: 16px;
font-size: var(--font-size);
}
위와 같이 계속해서 하드코딩하는 것은 효율적이지 못하다. 코드 양이 방대해질 경우 일일이 수정하기 어렵기 때문이다. 다행히 CSS에서도 이러한 것을 방지하고 재사용성을 높이기 위해 변수를 사용할 수 있다.
기본 사용법
.first-list {
background-color: thistle;
color: whitesmoke;
margin-left: 8px;
--font-size: 32px;
}
.first-list li {
font-size: var(--font-size);
}
.second-list {
background-color: thistle;
color: whitesmoke;
margin-left: 16px;
font-size: var(--font-size);
}
변수로 지정되길 원하는 속성에다가 --을 앞에 붙여주면 된다. --font-size과 같이 하면 된다. 그리고 해당 변수를 사용할 때는 var로 가둬줘야 한다. var(--font-size)처럼 말이다. 그리고 CSS 변수는 본인과 자식 요소에게 적용이 된다. 따라서 .second-list에서의 --font-size는 작용하지 않는다.
:root {
--font-size: 32px;
--background-color: thistle;
--text-color: whitesmoke;
}
.first-list {
background-color: var(--background-color);
color: var(--text-color);
margin-left: var(--base-space ,8px);
font-size: var(--font-size);
}
.second-list {
background-color: var(--background-color);
color: var(--text-color);
margin-left: calc(var(--base-space) * 2);
font-size: var(--font-size);
}
@media screen and (max-width: 768px) {
:root {
--font-size: 16px;
--background-color: blue;
--text-color: white;
--base-space: 4px;
}
}
이렇게 어느 곳에는 적용 되고, 어느 곳에는 적용이 안되는 것을 방지하기 위해 가장 최상위의 요소(root)에다가 CSS 변수를 선언한다.
이제, 변경하고 싶은 style이 있다면 :root에서 수치만 변경하면 된다. 그리고 변수명은 어디에 사용되는 변수인지 직관적으로 알 수 있게 지어줘야 한다.
미디어 쿼리에서도 응용이 가능하다. 화면의 크기가 768px보다 작아지게 되면 해당 CSS 변수가 적용되게 된다.
기본값
.first-list {
margin-left: var(--base-space, 8px);
}
만약 해당 변수를 찾을 수 없다면 두 번째 인자로 기본값을 줘서 적용해줄 수도 있다.
Custom Properties MDN : https://developer.mozilla.org/ko/docs/Web/CSS/Using_CSS_custom_properties