Thuộc tính grid-template-rows định nghĩa số lượng và kích thước các hàng (rows) trong CSS Grid Layout. Tương tự grid-template-columns nhưng cho trục dọc.
Cú pháp
.container {
display: grid;
grid-template-rows: <track-size> <track-size> ...;
}
Ví dụ: 3 hàng với chiều cao cố định
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: grid;
background-color: #95a5a6;
grid-template-rows: 120px 90px 100px; /* 3 hàng: 120px, 90px, 100px */
padding: 20px;
gap: 20px;
}
.container > div {
background-color: #f1c40f;
border: 2px solid #95a5a6;
padding: 35px;
font-size: 30px;
text-align: center;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>Game Board</h1>
<div class="container">
<div class="ele1">1</div>
<div class="ele2">2</div>
<div class="ele3">3</div>
<div class="ele4">4</div>
<div class="ele5">5</div>
<div class="ele6">6</div>
</div>
</body>
</html>
Các loại giá trị track size
| Loại | Ví dụ | Mô tả |
|---|---|---|
| Length | 100px, 5rem | Kích thước cố định |
| Percentage | 50% | Tỷ lệ chiều cao container |
| Fraction (fr) | 1fr, 2fr | Phần của không gian còn lại |
| Auto | auto | Kích thước theo content |
| min-content | min-content | Nhỏ nhất chứa content |
| max-content | max-content | Lớn nhất chứa content |
| minmax() | minmax(100px, 1fr) | Range: min đến max |
| fit-content() | fit-content(300px) | Min(max-content, max) |
Ví dụ nâng cao
.layout {
display: grid;
grid-template-rows:
auto /* Header: theo content */
1fr /* Main: chiếm phần còn lại */
auto /* Footer: theo content */
minmax(50px, 200px); /* Sidebar area: min 50px, max 200px */
min-height: 100vh;
}
Repeat() cho hàng lặp lại
.grid {
display: grid;
grid-template-rows: repeat(4, 1fr); /* 4 hàng bằng nhau */
grid-template-rows: repeat(3, 100px 50px); /* Pattern: 100, 50, 100, 50, 100, 50 */
grid-template-rows: repeat(auto-fill, minmax(100px, auto)); /* Auto rows */
}
Kết hợp với grid-template-columns
.holy-grail {
display: grid;
grid-template-columns: 200px 1fr 200px;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
gap: 1rem;
}
header { grid-column: 1 / -1; }
footer { grid-column: 1 / -1; }