styled-components에서 css 변수 사용

styled-components에서 css 사용하기

styled-components를 사용하면서 공통된 css가 있을 수 있습니다. 자주 사용하는 css를 변수로 선언하고 styled-components에서 재사용 할 수 있습니다.

사용방법

1
2
3
4
5
6
7
import { css } from 'styled-components';

export const flexCenterAlign = css`
display: flex;
align-items: center;
justify-content: center;
`;

flex를 이용하여 중앙 정렬하는 css를 자주 사용해서 styleConstants.ts파일 생성 후 flexCenterAlign변수를 선언 후 export 해줍니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import React from 'react';
import { flexCenterAlign } from 'styles/styleConstants';
import styled from 'styled-components';

const CenterAlign = styled.div`
width: 100px;
height: 100px;
border: 1px solid black;
margin: 10px;
${flexCenterAlign}
`;

export default (): JSX.Element => {
return (
<>
<CenterAlign>
중앙 정렬
</CenterAlign>
</>
);
}

템플릿 리터럴 문법에선 백틱(``)안에 표현식삽입법(${})를 이용하여 변수를 사용 할 수 있습니다. 따라서 flexCenterAlign변수를 불러와 해당 변수의 css를 사용 할 수 있습니다.

위와 같이 중앙 정렬 textflexCenterAlign변수의 값을 사용하여 가운데 정렬된 것을 볼 수 있습니다.

공유하기