본문 바로가기
Mark Up/CSS

[CSS] Chapter 11. 레이아웃 만들기 - grid

by song.ift 2022. 12. 29.

 

3. grid

<div class="container">
  <div class="top"></div>
  <div class="left"></div>
  <div class="right"></div>
  <div class="botoom"></div>
</div>
.container {
  width: 400px;
  height: 600px;
  border: 1px solid black;
}

.top {
  background: red;
  width: 400px;
  height: 200px;
}

.left {
  background: blue;
  width: 200px;
  height: 200px;
}

.right {
  background: green;
  width: 200px;
  height: 200px;
}

.bottom {
  background: purple;
  width: 400px;
  height: 200px;
}

 

grid로 정렬하는 방법은 제일 최신에 나온 방법이다. grid 같은 경우는 공간을 이미 다 격자로 나누어놓은 다음에 그 격자에 해당하는 것만큼 채워주는 방식으로 진행된다.

.container {
  width: 400px;
  height: 600px;
  border: 1px solid black;
  
  display: grid;  // 속성 명시
  grid-template-colums: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

위에 코드는 4등분을 해줬다. fr은 width로 n을 나누기 했을 때, 자동으로 계산되는 단위이다.

만약 width가 400px로 grid-template-colums: 100px 1fr 이면 400px - 100px = 300px로 1fr은 300px다.

물론 px로도 부여할 수 있다.

.container {
  width: 400px;
  height: 600px;
  border: 1px solid black;
  
  display: grid;  // 속성 명시
  grid-template-colums: 200px 200px;
  grid-template-rows: 200px 200px 200px;
}

 

그 후, 만들어 놓은 격자에 gird-template-areas를 통해 어떤 태그들이 들어가는지 정의를 해줘야한다.

.container {
  width: 400px;
  height: 600px;
  border: 1px solid black;
  
  display: grid;  // 속성 명시
  grid-template-colums: 200px 200px;
  grid-template-rows: 200px 200px 200px;
  grid-template-areas:
  "top top"
  "left right"
  "bottom bottom";
}

.top {
  background: red;
  width: 400px;
  height: 200px;
  
  grid-area: top;
}

.left {
  background: blue;
  width: 200px;
  height: 200px;
  
  grid-area: left;
}

.right {
  background: green;
  width: 200px;
  height: 200px;
  
  grid-area: right;
}

.bottom {
  background: purple;
  width: 400px;
  height: 200px;
  
  grid-area: bottom;
}

 

grid를 사용했을 때, 주의해야할 점이 있다.

위의 코드는 자식인 top, left, right, bottom에 각각 명시적으로 width와 height를 지정해줬는데, 그렇게 되면 의도한 값이랑 다르게 나올 수가 있다. 그래서 단순한 방법은 명시적으로 설정해놓은 걸 제거해버리고, 부모인 container가 설정한 width, height 값에 grid가 설정한 공간에 따라 크기가 유연하게 변경되는 것이 좋다. 그렇게 되면 html의 div 레이아웃의 순서를 고려하지 않아도 된다. 어짜피 areas에서 결정하기 때문이다.

제거를 해버리지 않고, width : auto를 사용해도 가능하다.

.container {
  width: 400px;
  height: 600px;
  border: 1px solid black;
  
  display: grid;  // 속성 명시
  grid-template-colums: 200px 200px;
  grid-template-rows: 200px 200px 200px;
  
  // 자식 width와 height를 제거해줬으니
  // html에서 고려한대로 테그의 레이아웃 순서를 무조건 따를 필요가 없다.
  grid-template-areas:
  "top right"
  "bottom right"
  "left right";
}

.top {
  background: red;
  grid-area: top;
}

.left {
  background: blue;
  grid-area: left;
}

.right {
  background: green;
  grid-area: right;
}

.bottom {
  background: purple;
  grid-area: bottom;
}

 

grid는 가장 최근에 나온 css이기도 하며, 앞선 방식과는 별개로 개발자 입맛대로 정의를 할 수 있다.

grid의 강점이 개발자가 레이아웃을 미리 만들어두고, 그것에 따라서 컨텐츠를 할당하는게 좋다고 생각한다.

댓글