HTML - CSS Grid Layout

Jan 18, 2024
HTML - CSS Grid Layout
 
notion image
 
CSS Grid는 행(row)과 열(column)의 그리드를 사용하여 웹 페이지를 디자인할 수 있다. 그리드를 사용하면 복잡한 레이아웃도 쉽게 디자인할 수 있다.

1. Grid Layout 사용하기

 
<!DOCTYPE html> <html lang="en"> <head> <style> .outer-box { width: 500px; height: 500px; background-color: skyblue; display: grid; } .inner-box { width: 100px; height: 100px; background-color: red; } </style> </head> <body> <div class="outer-box"> <div class="inner-box">1</div> </div> </body> </html>
notion image
 
부모 클래스 outer-box 와 자식 클래스 inner-box 가 있다. outer-box 내에서 inner-box 를 배치해보자. 아우터 박스의 디스플레이를 grid 로 설정했다. grid 는 가로-세로 방향으로 배치가 가능한 레이아웃 시스템이다.
 
justify-content: ; align-items: ;
justify-content 는 수평 정렬, align-items 는 수직 정렬이다. 각 값은 start, center, end 를 넣을 수 있고 둘다 center를 입력하면 빨간 박스가 가운데로 온다
notion image
 
 
 

2. 비율 나누기

grid-template-columns: 1fr 1fr;
notion image
 
grid-template-columns 는 그림과 같이 행의 열을 나눈다. fr은 fraction 로 숫자의 배율대로 세로 칸을 나눈다. 1fr 1fr 은 그림과 같이 2개의 열로 나눈다는 의미이다.
원하는 2fr 1fr 1fr 같이 비율을 정해서 나눌 수도 있고, 100px 1fr 1fr 처럼 길이를 정할 수도 있다.
auto auto auto 로 정하면 자동으로 비율이 정해진다.
 
새로운 박스를 추가해보자.
 
<!DOCTYPE html> <html lang="en"> <head> <style> .outer-box { width: 500px; height: 500px; background-color: skyblue; display: grid; grid-template-columns: 1fr 1fr; } .inner-box1 { width: 100px; height: 100px; background-color: red; } .inner-box2 { width: 100px; height: 100px; background-color: blue; } .b1 { display: grid; } .b2 { display: grid; } </style> </head> <body> <div class="outer-box"> <div class="b1"> <div class="inner-box1">1</div> </div> <div class="b2"> <div class="inner-box2">2</div> </div> </div> </body> </html>
notion image
 
파란색 박스를 추가했다. grid 로 outer-box 를 나눌 때, inner-box 를 각각 새로운 부모 박스를 만들어서 감쌌다. 그러면 부모 박스의 위치를 변경하면 inner-box 도 같이 움직인다.
 
.b1 { display: grid; justify-content: end; align-items: start; } .b2 { display: grid; justify-content: start; align-items: end; }
notion image
 
outer-box 가 반으로 나눠졌기 때문에 inner-box 를 끝으로 이동해도 나눠진 위치까지만 이동한다.
 
 
 
Share article
RSSPowered by inblog