Introduction
Styled-components 를 이용하여 Grid로 반응형을 구현하는 법을 알아보려 한다.
1. theme에 break point 설정
desktop, tablet, mobile에 대한 break point를 정하고 theme에 다음과 같이 설정해준다.
// PC: 1024px ~
// tablet: 768px ~ 1023.9px
// mobile: ~ 767.9px
const theme = {
media: {
desktop: '@media screen and (min-device-width: 1024px)',
tablet: '@media screen and (min-device-width: 768px) and (max-device-width: 1023.9px)',
mobile: '@media screen and (max-device-width: 767.9px)',
}
};
export default theme;
2. _app.tsx에 theme 적용
next.js를 사용하기 때문에 _app.tsx에 theme을 적용해줘야한다.
import theme from "@/styles/theme";
export default function App({ Component, pageProps }) {
return (
<RecoilRoot>
<ThemeProvider theme={theme}>
...생략
</ThemeProvider>
</RecoilRoot>
);
}
3. styled-components 컴포넌트에 적용
const FindContent = styled.div`
display: grid;
grid-gap: 20px;
${({theme}) => theme.media.desktop}{
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: auto auto auto;
}
${({theme}) => theme.media.tablet}{
grid-template-columns: 1fr 1fr;
grid-template-rows: auto auto auto;
}
${({theme}) => theme.media.mobile}{
grid-template-columns: 1fr;
grid-template-rows: repeat(6, auto);
}
`;
const FindBox = styled.div`
border: 1px solid #000;
height: 491px;
width: 100%;
`;
총 6개의 컴포넌트에 대한 배치를 Grid로 나타낸다.
Grid에 대하여 아주 간단히만 설명하자면, 요소들을 2차원으로 배치하는 방법이다.
따라서 column, row를 각각 설정하여 2차원 평면 원하는 위치에 요소를 배치할 수 있다.
grid-template-columns
- 요소들을 가로로 배치하는 방식을 정한다.
- 1fr은 100%의 width중 1의 배율로 요소 크기가 정해진다.
- 예를 들어 1fr 1fr 1fr 라면 아이템의 width는 각각 33.333..%가 된다.
grid-template-rows
- 요소들을 세로로 배치하는 방식을 정한다.
결과
'Frontend > HTML&CSS' 카테고리의 다른 글
[HTML & CSS] CSS Grid minmax로 내부 요소 비율 유지하기 (feat. text 말줄임표 처리) (2) | 2024.06.23 |
---|---|
[html & css] 드래그 방지 (0) | 2023.02.19 |
[HTML/CSS] flex 사용 시 가운데 정렬 (0) | 2022.12.07 |
[HTML/CSS] 네이버 메뉴바 (0) | 2022.11.10 |