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

CSS Grid Elements - Phần tử lưới (Container & Items)

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ínhChức năng
display: grid / inline-gridKí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-templateShorthand
grid-auto-columns/rowsKích thước track tự động
grid-auto-flowThuật toán auto-placement
gap / row-gap / column-gapKhoảng cách tracks
justify-items / align-itemsCăn items trong cell
justify-content / align-contentCăn grid trong container

Grid Item Properties

Thuộc tínhChức năng
grid-column-start/endVị trí cột (line numbers)
grid-row-start/endVị trí hàng
grid-column / grid-rowShorthand
grid-areaShorthand đầy đủ hoặc tên area
justify-self / align-selfCăn item trong cell
z-indexThứ 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)