Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Vai trò CSS Grid Container

CSS Grid Container - Container lưới

Khi một element có `display: grid` (hoặc `inline-grid`), nó trở thành **Grid Container**. Các con trực tiếp trở thành **Grid Items**. Grid Container định nghĩa **cấu trúc lưới** (hàng, cột, gap) thông qua các thuộc tính grid-*.

Thuộc tính chính của Grid Container

Thuộc tínhChức năng
display: grid / inline-gridKích hoạt Grid Container
grid-template-columnsĐịnh nghĩa cột (số lượng, kích thước)
grid-template-rowsĐịnh nghĩa hàng (số lượng, kích thước)
grid-template-areasĐặt tên vùng (named areas)
grid-templateShorthand cho rows + columns + areas
grid-auto-columnsKích thước cột ngầm (implicit)
grid-auto-rowsKích thước hàng ngầm
grid-auto-flowThuật toán auto-placement (row/column/dense)
gap / row-gap / column-gapKhoảng cách giữa cell
justify-items / align-itemsCăn chỉnh item trong cell (mặc định stretch)
justify-content / align-contentCăn chỉnh toàn bộ lưới trong container

Ví dụ: Grid Container cơ bản (2 cột)

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      display: grid;
      background-color: blue;
      grid-template-columns: auto auto;  /* 2 cột auto */
      padding: 20px;
      grid-gap: 20px;                    /* gap cũ, dùng gap mới */
    }
    .container > div {
      background-color: orange;
      border: 2px solid gray;
      padding: 35px;
      font-size: 30px;
      text-align: center;
    }
  </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>

Implicit vs Explicit Grid

  • Explicit Grid: Được định nghĩa bởi `grid-template-rows/columns/areas`.
  • Implicit Grid: Tự động tạo khi item nhiều hơn track đã định nghĩa. Kích thước bởi `grid-auto-rows/columns` (mặc định `auto`).

Grid Container vs Flex Container

Đặc điểmFlexboxGrid
Chiều1 chiều (row HOẶC column)2 chiều (row VÀ column)
Content-first✅ Item quyết định size❌ Container quyết định track
Layout-first❌✅ Container định nghĩa structure
OverlapKhó (cần position)Dễ (grid-column/row overlap)
Phù hợpComponent, navigation, formPage layout, card grid, dashboard

Lưu ý

  • Chỉ **con trực tiếp** (direct children) của Grid Container mới là Grid Items.
  • Text node con trực tiếp cũng thành anonymous grid item (thường không mong muốn).
  • `display: grid` tạo **Block Formatting Context** (chống margin collapse).