CSS Grid 속성
Grid란?
웹페이지를 위한 두 방향(x축, y축) 2차원 레이아웃 시스템으로, 자식 요소들이 컨테이너 안 공간을 맞추기 위해 크기를 설정하는 방법이다.
grid 레이아웃을 만들기 위한 기본적인 HTML구조는 다음과 같다.
<div class="container">
<div class="item">A</div>
<div class="item">B</div>
<div class="item">C</div>
<div class="item">D</div>
<div class="item">E</div>
<div class="item">F</div>
</div>
부모 요소인 div.container를 Grid Container(그리드 컨테이너)라고 부르고, 자식 요소인 div.item들을 Grid Item(그리드 아이템)이라고 부른다. “컨테이너가 Grid의 영향을 받는 전체 공간이고, 설정된 속성에 따라 각각의 아이템들이 어떤 형태로 배치되는 것”이라고 생각하면 된다.
Grid 용어 정리

- 그리드 트랙 (Grid Track) : Grid의 행(Row) 또는 열(Column)
- 그리드 셀 (Grid Cell) : Grid의 한 칸을 가리킨다. <div>같은 실제 html 요소는 그리드 아이템이고, 이런 Grid 아이템 하나가 들어가는 “가상의 칸(틀)”이라고 생각하면 된다.
- 그리드 라인(Grid Line) : Grid 셀을 구분하는 선
- 그리드 번호(Grid Number) : Grid 라인의 각 번호
- 그리드 갭(Grid Gap) : Grid 셀 사이의 간격
- 그리드 영역(Grid Area) : Grid 라인으로 둘러싸인 사각형 영역으로, 그리드 셀의 집합이다.
Grid 속성과 사용
grid의 속성들은 flex와 마찬가지로 컨테이너에 적용하는 속성과 아이템에 적용하는 속성으로 나뉜다.
컨테이너(Grid Container)에 적용하는 속성
display: grid;
Grid 컨테이너에 display: grid;를 적용하는 게 시작이다. 아이템들이 block 요소라면 이 한 줄 만으로는 딱히 변화는 없다.
.container {
display: grid;
/* display: inline-grid; */
}
inline-grid는 inline-block처럼 동작하며 아이템의 배치와 관련이 있다기보다는 컨테이너가 주변 요소들과 어떻게 어우러질지를 결정한다.
grid-template-rows, grid-template-columns - 그리드 형태 정의
grid-template-rows : 행 방향 그리드 트랙의 사이즈를 설정
grid-template-columns : 열 방향 그리드 트랙의 사이즈를 설정
.container {
grid-template-columns: 200px 200px 500px;
/* grid-template-columns: 1fr 1fr 1fr */
/* grid-template-columns: repeat(3, 1fr) */
/* grid-template-columns: 200px 1fr */
/* grid-template-columns: 100px 200px auto */
grid-template-rows: 200px 200px 500px;
/* grid-template-rows: 1fr 1fr 1fr */
/* grid-template-rows: repeat(3, 1fr) */
/* grid-template-rows: 200px 1fr */
/* grid-template-rows: 100px 200px auto */
}
컨테이너에 grid 트랙의 크기들을 지정해 주는 속성으로 여러 가지 단위를 사용할 수 있고, 섞어서 사용도 가능하다.
* 단위 fr - fraction: 분수 - 컨테이너를 분할
grid 컨테이너 안에서 트랙의 비율을 지정해 주는 유연한 길이 단위로 1fr 1fr 1fr은 1:1:1의 비율을 의미한다.
* 함수 - repeat(반복 횟수, 반복값)
row 혹은 column 방향으로 grid-track의 사이즈를 좀 더 간단한 형태로 표현하도록 도와주는 CSS 함수이다. 함수에 전달하는 첫 번째 인자는 반복 횟수(repeat count), 두 번째 인자는 반복할 값이다. repeat(3, 1fr)은 1fr 1fr 1fr과 같다. repeat(3, 1fr 4fr 2fr); 이런 식의 패턴도 가능하다.
* 함수 - minmax
최솟값과 최댓값을 지정할 수 있는 함수이다. minmax(100px, auto)로 예를 들어보자. minmax(100px, auto)의 의미는 최소한 100px, 최대는 자동으로(auto) 늘어나게 이다. 아무리 내용의 양이 적더라도 최소한 높이 100px은 확보하고, 내용이 많아 100px이 넘어가면 알아서 늘어나도록 처리해 준다.
.container {
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(3, minmax(100px, auto));
}
행 방향 그리드 트랙의 최소 높이는 100px, 최대 높이는 auto로 콘텐츠 크기만큼의 높이를 차지한 것을 확인할 수 있다. 열 방향 그리드 트랙에 적용할 경우 트랙 넓이의 최소, 최대를 결정하게 된다.
auto-fill & auto-fit
auto-fill과 auto-fit은 column의 개수를 미리 정하지 않고 설정된 너비가 허용하는 최대 개수로 셀을 채운다.
auto-fill: 가능한 많은 셀들을 넣고 남는 빈 공간이 생긴다.
auto-fit: 가능한 많은 셀들을 넣고 공간이 남을 경우, 그 공간을 각 셀들이 나눠 갖는다.
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(20%, auto));
/* grid-template-columns: repeat(auto-fit, minmax(20%, auto)); */
background-color: aquamarine;
grid-auto-rows: minmax(100px, auto);
gap: 10px;
}
gap
셀과 셀사이의 간격을 설정할 때 사용 할 수 있는 속성으로 복잡한 레이아웃 안에서 마진 대신 편리하게 간격을 설정할 수 있다. (row, column 각각 지정할 수 있으며, 한 번에 지정도 가능하다.)
.container {
row-gap: 10px;
/* row의 간격을 10px로 */
column-gap: 20px;
/* column의 간격을 20px로 */
gap: 10px 20px;
/* row-gap: 10px; column-gap: 20px; */
}
grid-auto-columns, grid-auto-rows - 그리드 형태를 자동으로 정의
열, 행의 개수를 미리 알 수 없는 경우 사용한다. grid-template-columns(또는 grid-template-rows)의 통제를 벗어난 위치에 있는 트랙의 크기를 지정하는 속성이다. 굳이 횟수를 지정해서 반복할 필요 없이 “알아서” 처리된다.
.container {
display: grid;
grid-auto-rows: minmax(100px, auto);
grid-template-columns: repeat(auto-fit, minmax(20%, auto));
background-color: aquamarine;
grid-gap: 10px;
}
grid-auto-flow - 아이템이 자동 배치되는 흐름을 결정하는 속성
그리드에 명시적으로 배치(레이아웃) 되지 않은 아이템이 있을 경우, 자동 배치 알고리즘이 실행되어 자동으로 배치되도록 설정할 수 있다. 속성 값에 따라 자동 배치 알고리즘 작동 방식이 달라진다.
▼ 속성값
row - 각 행을 차례로 채우고 필요에 따라 새 행을 추가하는 자동배치 알고리즘.
column - 각 열을 차례로 채우고 필요에 따라 새 열을 추가하는 자동 배치 알고리즘.
dense - 배치 중 나중에 크기가 작은 아이템이 존재할 경우, 그 리드 영역 앞부분의 남은 공간에 자동 배치하는 알고리즘
참고자료:https://yamoo9.gitbook.io/css-grid/css-grid-guide/grid-auto-flow
Grid 자동 흐름 설정 - CSS Grid Layout Guidebook
그리드에 명시적으로 배치(레이아웃) 되지 않은 아이템이 있을 경우, 자동 배치 알고리즘이 실행되어 자동으로 배치 되도록 설정할 수 있습니다. 속성 값에 따라 자동 배치 알고리즘 작동 방식
yamoo9.gitbook.io
align-content
그리드 콘텐츠의 수직(열) 정렬( 그리드 콘텐츠의 세로 높이가 그리드 컨테이너보다 작아야 한다.)
속성값 : stretch, center, start, end, space-around, space-between, space-evenly
justify-content
그리드 콘텐츠의 수평(행) 정렬(그리드 콘텐츠의 가로 너비가 그리드 컨테이너보다 작아야 한다.)
속성값 : stretch, center, start, end, space-around, space-between, space-evenly
align-items
직계 자식에 대한 수직(열) 정렬을 모두 동일하게 준다.
속성값 : stretch, center, start, end
justify-items
직계 자식에 대한 수평(열) 정렬을 모두 동일하게 준다.
속성값 : stretch, center, start, end
place-items
align-items와 justify-items를 같이 쓸 수 있는 단축 속성
place-items: center start;
아이템(Grid Item)에 적용하는 속성
grid-area
grid-column-start, grid-column-end, grid-row-start, grid-row-end
그리드 라인 번호를 이용해 column과 row의 범위를 결정한다. start에 시작 라인 번호 end에 끝나는 라인 번호를 넣는다.
.item.a {
background-color: gold;
border: 1px solid royalblue;
/* 행, 열 시작과 끝 각각 지정 */
grid-row-start: 1;
grid-row-end: 2;
grid-column-start: 1;
grid-column-end: 4;
/* 행, 열 각각 합쳐서 지정 */
grid-row: 1/2;
grid-column: 1/4;
/* 행, 열 한번에 합쳐서 지정 */
grid-area: 1/1/2/4;
/* span을 사용할 경우 시작라인부터 몇개의 셀을 차지할것인지를 지정 */
grid-area: 1/1/1/span 3;
}
grid-template-areas / grid-area
grid-template-areas 속성값으로 영역을 나눠두고 그 영역에 해당되는 값을 자식요소에게 적용한다.
" "로 한 행을 나타냄
.container{
grid-template-areas:
"header header header"
"section section aside"
"footer footer footer"
}
header{
grid-area:header;
}
위의 두 가지 방법으로 아래의 레이아웃 예제를 구성해 보자! (개발자 도구창에서 그리드 눌러 그리드 라인 확인이 가능하다.)
첫 번째 방법은 grid-template-columns, grid-template-rows, grie-area를 사용하는 방법이다.
코드는 아래와 같다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid</title>
<style>
.container {
width: 500px;
height: 500px;
display: grid;
grid-template-columns: repeat(4,1fr);
grid-template-rows: repeat(5,1fr);
background-color: rgb(255, 255, 255);
gap: 10px;
}
.item-a{
background-color: gold;
grid-area: 1/1/3/2;
}
.item-b{
background-color: rgb(255, 154, 167);
grid-area: 1/2/3/4;
}
.item-c{
background-color: rgb(140, 213, 239);
grid-area: 1/4/4/6;
}
.item-d{
background-color: rgb(142, 125, 255);
grid-area: 3/1/5/3;
}
.item-e{
background-color: rgb(255, 194, 245);
grid-area: 5/1/6/3;
}
.item-f{
background-color: rgb(255, 72, 0);
grid-area: 3/3/6/4;
}
.item-g{
background-color: rgb(153, 240, 96);
grid-area: 4/4/6/6;
}
</style>
</head>
<body>
<div class="container">
<div class="item-a">A</div>
<div class="item-b">B</div>
<div class="item-c">C</div>
<div class="item-d">D</div>
<div class="item-e">E</div>
<div class="item-f">F</div>
<div class="item-g">G</div>
</div>
</body>
</html>
두 번째 방법은 grid-template-areas / grid-area를 사용하는 방법이다.
코드는 아래와 같다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grid</title>
<style>
.container {
width: 500px;
height: 500px;
display: grid;
grid-template-areas:
"a b b c"
"a b b c"
"d d f c"
"d d f g"
"e e f g";
background-color: rgb(255, 255, 255);
gap: 10px;
}
.item-a{
background-color: gold;
grid-area: a;
}
.item-b{
background-color: rgb(255, 154, 167);
grid-area: b;
}
.item-c{
background-color: rgb(140, 213, 239);
grid-area: c;
}
.item-d{
background-color: rgb(142, 125, 255);
grid-area: d;
}
.item-e{
background-color: rgb(255, 194, 245);
grid-area: e;
}
.item-f{
background-color: rgb(255, 72, 0);
grid-area: f;
}
.item-g{
background-color: rgb(153, 240, 96);
grid-area: g;
}
</style>
</head>
<body>
<div class="container">
<div class="item-a">A</div>
<div class="item-b">B</div>
<div class="item-c">C</div>
<div class="item-d">D</div>
<div class="item-e">E</div>
<div class="item-f">F</div>
<div class="item-g">G</div>
</div>
</body>
</html>
행의 수만큼 ""를 만들어 ""안에서 영역을 나눠주면 된다. (아이템 요소에 지정해 주는 이름값에는 따옴표가 없다! 주의!)
z-index
z-index 속성을 grid 안에서도 사용할 수 있음. grid 안에서는 굳이 position 속성을 사용하지 않더라도 화면에 보여지는 우선순위를 설정할 수 있다.
align-self
아이템 개별로 수직(열) 정렬을 지정
속성값 : stretch, center, star, end
justify-self
아이템 개별로 수평(행) 정렬을 지정
속성값 : stretch, center, star, end
place-self
align-self, justify-self를 함께 적는 단축속성
place-self: center end;
order
(flex와 마찬가지로) 아이템의 배치 순서를 지정. 수가 작을수록 더 우선순위를 받는다. 음수도 사용 가능
grid
단축속성
grid-template-rows, grid-template-columns, grid-template-areas, grid-auto-rows, grid-auto-columns, grid-auto-flow
grid: auto-flow / 1fr 1fr 1fr;
grid: auto-flow dense / 40px 40px 1fr;
'👩🏻💻Frontend > CSS' 카테고리의 다른 글
스크린 리더 사용자를 위한 기업의 CSS IR(Image Replacement) 기법 (0) | 2023.07.27 |
---|---|
CSS 변수, 함수 ( 사용자 지정 CSS 속성 ) (0) | 2023.07.15 |
웹 브라우저 렌더링 개념 - position transform 속성 차이 (1) | 2023.07.14 |
CSS Flex 정리 (0) | 2023.07.12 |
CSS 선택자 적용 우선순위 계산하기 (0) | 2023.07.11 |