스타일 컴포넌트로 전역 스타일 정의하기

리충녕·2023년 12월 16일

React

목록 보기
12/29

전역 스타일

css 초기 값은 브라우저별로 약간의 차이가 있기 때문에 초기화 해주는 과정이 필요하다.

전역 스타일링을 통해 기본적으로 부여된 스타일을 제거하거나 공통으로 부여할 스타일을 정의하는 것을 의미한다.

-globalStyle.tsx

* {
    box-sizing: border-box;
}
body {
  line-height: 1;
  font-family: 'Nanum Gothic', sans-serif;
  background-color: ${(props) => props.theme.bgColor};
  color : ${(props) => props.theme.textColor};
}
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;
}
a {
    text-decoration: none;
}

위 파일은 전역 스타일링을 정의한 것이다.

스타일링에 방해가 되는 속성을 미리 제거하는 작업인데 이러한 작업을 css reset이라 한다.

위와 같이 정의한 파일을 스타일 컴포넌트 라이브러리가 제공하는 createGlobalStyle() 함수를 사용해 전역에 적용될수 있도록 하는 것이다.


createGlobalStyle

createGlobalStyle() 함수를 통해 생성한 전역 스타일 컴포넌트를 최상위 컴포넌트에 추가하면 하위 컴포넌트에 해당 스타일이 적용된다.

  • globalStyle.tsx
import { createGlobalStyle } from "styled-components";

// reset css
export const GlobalStyle = createGlobalStyle`
// google fonts
@import url('https://fonts.googleapis.com/css2?family=Nanum+Gothic&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;
}
* {
    box-sizing: border-box;
}
body {
  line-height: 1;
  font-family: 'Nanum Gothic', sans-serif;
  background-color: ${(props) => props.theme.bgColor};
  color : ${(props) => props.theme.textColor};
}
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;
}
a {
    text-decoration: none;
}
`
  • App.tsx
const App = () => {
  return (
    <>
      <GlobalStyle />
      <Router />
    </>
  )
}

참고

노마드코더

0개의 댓글