본문 바로가기
Frontend/HTML&CSS

[styled-components] Grid로 반응형 구현

by 모너아링 2024. 1. 5.

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

  • 요소들을 세로로 배치하는 방식을 정한다.

 

결과