CSS Grid Layout bao gồm 2 loại phần tử chính: Grid Container (phần tử cha) và Grid Items (phần tử con trực tiếp).
Cấu trúc Grid
<div class="container"> <!-- Grid Container -->
<div class="item">1</div> <!-- Grid Items -->
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
</div>
Ví dụ: Grid 2 cột, 3 hàng (6 items)
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
grid-template-columns: auto auto; /* 2 cột tự động */
padding: 20px;
gap: 15px;
}
.ele {
background-color: #e67e22;
border: 2px solid #95a5a6;
padding: 25px;
font-size: 20px;
text-align: center;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>Game Board</h1>
<div class="container">
<div class="ele">1</div>
<div class="ele">2</div>
<div class="ele">3</div>
<div class="ele">4</div>
<div class="ele">5</div>
<div class="ele">6</div>
</div>
</body>
</html>
Grid Container Properties
| Thuộc tính | Chức năng |
display: grid / inline-grid | Kích hoạt Grid |
grid-template-columns | Định nghĩa cột |
grid-template-rows | Định nghĩa hàng |
grid-template-areas | Đặt tên vùng layout |
grid-template | Shorthand |
grid-auto-columns/rows | Kích thước track tự động |
grid-auto-flow | Thuật toán auto-placement |
gap / row-gap / column-gap | Khoảng cách tracks |
justify-items / align-items | Căn items trong cell |
justify-content / align-content | Căn grid trong container |
Grid Item Properties
| Thuộc tính | Chức năng |
grid-column-start/end | Vị trí cột (line numbers) |
grid-row-start/end | Vị trí hàng |
grid-column / grid-row | Shorthand |
grid-area | Shorthand đầy đủ hoặc tên area |
justify-self / align-self | Căn item trong cell |
z-index | Thứ tự z-axis khi overlap |
Implicit vs Explicit Grid
- Explicit Grid: Tracks định nghĩa bởi grid-template-rows/columns
- Implicit Grid: Tracks tự tạo khi items nhiều hơn tracks định nghĩa (kiểm soát bởi grid-auto-rows/columns)