개발

styled-components를 이용하여 전역 스타일을 줘보자!

썽연 2022. 5. 29. 21:50
728x90

styled-components는 전역스타일을 지정해 줄 수 있다.

컴포넌트 레벨 스타일링

React와 styled-components로 웹 개발을 하다보면 대부분의 경우 컴포넌트 레벨에서 스타일을 하게 된다.

 

각각 컴포넌트에서 스타일을 개별적으로 주면?

- 시간이 많이 걸리는 불편함
- 같은 코드를 쳐야할 수도 있다!

그래서 같은 스타일 코드는 전역으로 줘버리자~~

 

Styled Components는 createGlobalStyle() 함수를 제공한다.

GlobalStyle사용하는 이유는?
- 규모가 큰 웹 개발 할 때에, 개별 컴포넌트가 아닌, 모든 컴포넌트에 동일한 스타일을 적용하는 편이 유리할 수 있다.

 

// src/App.tsx

import Router from "./Router";
import {createGlobalStyle} from "styled-components"

const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@300;400&display=swap');
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, menu, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
main, menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, main, menu, nav, section {
  display: block;
}
/* HTML5 hidden-attribute fix for newer browsers */
*[hidden] {
    display: none;
}
body {
  line-height: 1;
}
menu, ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
* {
  box-sizing: border-box;
}
body {
  font-family: 'Source Sans Pro', sans-serif;
  background-color:${(props) => props.theme.bgColor};
  color:${(props) => props.theme.textColor}
}
a {
  text-decoration:none;
}
`;

function App() {
  return (
        <> 
            <GlobalStyle/>
            <Router />
        </>
    )
}

export default App;

App.tsx를 위와 같은 코드로 지정해주고, GlobalStyle을 호출하여준다.


flatuicolors에서 컬러값 가져올 수 있으니 색상이 궁금할 때 참고하자.

728x90