[CSS] :root 를 활용한 전역 스타일링 설정

slight-snow·2023년 7월 20일
0

CSS

목록 보기
3/3
post-thumbnail

예를 들어, 같은 스타일링을 적용한 태그가 여러개 있다고 가정해보자!

// JavaScript
function Example () {
	return (
    	<>
      		<div className="box-01"></div>
      		<div className="box-02"></div>
      		<div className="box-03"></div>
        </>
    );
}

export default Example;
/* CSS */
.box-01 {
	width: 40px;
    height: 40px;
    background-color: red;
}

.box-02 {
	width: 40px;
    height: 40px;
    background-color: yellow;
}

.box-03 {
	width: 40px;
    height: 40px;
    background-color: green;
}

box-01, box-02, box-03 모두 background-color 속성이 모두 다른 색으로 설정되어 있다.
만약 box-01, box-02, box-03 세 가지 태그 모두 같은 색으로 구성되어야 한다면 어떨까?

단순히 background-color 속성을 같은 색으로 설정하면 된다고 생각할 수 있지만,
background-color: red;, background-color: red;, background-color: red; ...
이와 같이 작성을 해두면 나중에 속성을 변경해야할 일이 생겼을 때 모두 하드코딩으로 수정해야한다.

그렇기에 변수를 만들어 속성에 할당해두는 편이 나중에 유지/보수하는 데에 훨씬 수월할 것이다 :)
그때 사용할 수 있는 방법이 바로 :root 다!

:root는 최상단의 전역 스타일링인 index.css에 작성하면 모든 페이지, 컴포넌트에 쓸 수 있다.

// CSS index.css
:root {
	--backgroundColor: #000000;
}

이렇게 작성해두면 이후 다른 CSS 파일에서 작성할 때, attribute: var(value name); 형식으로 적어주면 된다.
앞선 예시와 :root 사용방법을 활용하여 표현하면 아래와 같은 CSS 코드가 될 것이다.

/* CSS */
.box-01 {
	width: 40px;
    height: 40px;
    background-color: var(--backgroundColor);
}

.box-02 {
	width: 40px;
    height: 40px;
    background-color: var(--backgroundColor);
}

.box-03 {
	width: 40px;
    height: 40px;
    background-color: var(--backgroundColor);
}

이렇게 해두면 나중에 최상단인 index.css에서 --backgroundColor의 값만 수정해주면
해당 값을 적용한 다른 모든 컴포넌트나 엘리먼트를 동시에 수정할 수 있다 :)

매번 하드코딩으로 바꿔가던 나를 되돌아보며.. 앞으로 :root를 사용하여 효율적인 스타일링을 해보자!

profile
주니어 개발자의 기억을 위한 기록 :)

0개의 댓글