CSS custom property

joonyg·2021년 12월 24일
0

HTML&&CSS

목록 보기
6/8

Css Custom Property

:root { 
	--color-text: black;
	--color-background: lightgray;
}
  • 위와 같이 --와 css property 처럼 변수를 선언할 수 있고 이를 CSS Custom property라고 부른다.
  • 해당 변수/custom property는 var()이라는 keyword와 같이 사용하여 다른 css property에 대해 사용할 수 있다.
    - var( custom property, default 값 )으로 2개 이상의 인자를 주어 custom property가 정의 되지 않은 경우 default값을 css 속성으로 할당할 수 있다.
    - 일종의 fallback
  • custom property의 장점 중 하나로는 프로그래밍 언어 처럼 자식 요소로, 즉 lexical bounding이 되는 것처럼 그대로 inherit된다는 점이다.
  • custom property는 -- 로 시작해야 함에 유의!
  • html의 인라인 style로도 정의할 수 있다!!
    - < div style={--i : 0}> </ div >

  • :root : root selector는 항상 최상위 요소, 즉 html의 ref를 가지고 있다. 즉, 전역에서 사용할 변수들은 html태그에서 custom property를 이용해 정의할 수 있다.
    - Sass에서는 _color.scss에는 const값, custom property로는 component별로 똑같이 쓰이지만 값이 달라지는 부분에 사용하면 유용하다.
    - --padding등을 지정하는 경우 등을 예시로 들 수 있겠다.
    - media query에서도 custom property의 값만 바꾸어 주면 된다.


React와 styled-components 에서의 활용

  • 통상 styled-components에서는 props와 theme에 따라 같은 객체형태에 따라 조건을 검사하고 그에 따라 다른 스타일을 적용한다.
background: ${(props) => props.theme.colors.primary};

color: ${( props ) => props.red ? "red" : "black" }
  • custom property를 사용한다면 color : var(--custom)으로 굉장히 짧게 작성할 수 있을 뿐더러 theme 객체 대신에 global.css에서 :root (html)에 대해 custom property를 미리 설정해 두면 되므로 훨씬 쉬워질 것이다. (theme을 import하는 등 번거로운 작업 단축)

In Media query

const Button = styled.button`
  /* default button styles */
	
  /* Mobile height */
  height: 48px;
  
  /* Desktop height */
  @media (min-width: ${(props) => props.theme.bp.desktop}) {
    height: 32px;
  }
`;
  • 앞서도 언급했듯이 media query에서 custom property는 유용히 쓰일 수도 있다.
  • 위의 예제는 Button에 대한 styled-component인데 props.theme.bp.desktop으로 해당 breakpoint에 대한 값을 props로 전달 받고 있다.
  • 이렇게 전역에서 쓰이는 값을 custom property를 활용한다면 아래와 같이 :root내에 breakpoint별로 해당하는 너비, 높이 값을 미리 지정해 줌으로서 단축할 수 있다.
const GlobalStyles = createGlobalStyle`
  html {
    --min-tap-target-height: 48px;
    @media (min-width: ${(props) => props.theme.bp.desktop}) {
      --min-tap-target-height: 32px;
    }
  }
`;

Button = styled.button `
	height: var(--min-tap-target-height);
`
  • :root (html)에 대해 media query 시행해 custom property에 대한 값만 변경하였고 Button에서는 media query를 따로 시행하지 않고 변수만 가져다 사용해 코드가 깔끔해 졌다.

Other Possibility

1) darkmode에 대해 색상등을 custom-property로 미리 지정하고 prefers-color-scheme에서 색상에 대한 custom-property값만 변경하면 다른 css 파일에서 바꿀 필요 없어진다.
2) Javascript에서 접근은 아래와 같다.

<!-- getComputedStyle -->
getComputedStyle(document.documentElement)
<!-- returns CSSStyleDeclaration about element  -->

<!-- getPropertyValue -->
CSSStyleDeclaration.getPropertyValue('--color-primary');
<!-- returns   -->

<!-- 2개 합친다! -->
getComputedStyle(document.documentElement).getPropertyValue('--color-primary');

참고 자료

https://www.joshwcomeau.com/css/css-variables-for-react-devs/
https://www.youtube.com/watch?v=nybATB2MoYI

profile
while( life ) { learn more; }

0개의 댓글