6. Global Style & Theme
Reset CSS
npm i styled-reset
<App/>
내부 최상단에 <Reset/>
을 넣어주면 기본적으로 적용되는 margin 등의 스타일이 사라짐
Global Style
아래의 설정들을 전역스타일로 지정해주자
box-sizing을 border box로 바꾸기
1rem을 16px이 아니라 10px로 바꾸기
font-size는 16px을 1rem으로
한국어 keep-all 설정
createGlobalStyle
로 컴포넌트를 만들어 <Reset/>
처럼 적용
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
html {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
html {
font-size: 62.5%;
}
body {
font-size: 1.6rem;
}
:lang(ko) {
h1, h2, h3 {
word-break: keep-all;
}
}
`;
export default GlobalStyle;
Theme
컴포넌트를 <ThemeProvider/>
로 감싸면 내부에서 theme을 사용할 수 있음
<ThemeProvider/>
는 context API를 이용하여 하위의 모든 컴포넌트들이 props.theme
을 사용할 수 있게 해줌
// Define our button, but with the use of props.theme this time
const Button = styled.button`
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
/* Color the border and text with theme.main */
color: ${props => props.theme.main};
border: 2px solid ${props => props.theme.main};
`;
// We are passing a default theme for Buttons that arent wrapped in the ThemeProvider
Button.defaultProps = {
theme: {
main: "palevioletred"
}
}
// Define what props.theme will look like
const theme = {
main: "mediumseagreen"
};
render(
<div>
<Button>Normal</Button>
<ThemeProvider theme={theme}>
<Button>Themed</Button>
</ThemeProvider>
</div>
);
theme props를 함수로도 넘길 수 있음
// Define our button, but with the use of props.theme this time
const Button = styled.button`
color: ${props => props.theme.fg};
border: 2px solid ${props => props.theme.fg};
background: ${props => props.theme.bg};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
`;
// Define our `fg` and `bg` on the theme
const theme = {
fg: "palevioletred",
bg: "white"
};
// This theme swaps `fg` and `bg`
const invertTheme = ({ fg, bg }) => ({
fg: bg,
bg: fg
});
render(
<ThemeProvider theme={theme}>
<div>
<Button>Default Theme</Button>
<ThemeProvider theme={invertTheme}>
<Button>Inverted Theme</Button>
</ThemeProvider>
</div>
</ThemeProvider>
);
Last updated