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

Định nghĩa số cột trong CSS Grid Layout (grid-template-columns)

Thuộc tính grid-template-columns

grid-template-columns xác định **số lượng và kích thước cột** trong CSS Grid Container. Mỗi giá trị = một cột. Có thể dùng đơn vị tuyệt đối, tương đối, `fr`, `auto`, `minmax()`, `repeat()`.

Cú pháp

grid-template-columns: <track-size>+;
/* track-size:  |  |  (fr) | minmax() | auto | max-content | min-content | fit-content() */

Ví dụ: Grid 3 cột bằng nhau

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      display: grid;
      background-color: yellow;
      grid-template-columns: auto auto auto;  /* 3 cột auto */
      padding: 20px;
      grid-gap: 20px;           /* gap giữa các cell */
    }
    .container > div {
      background-color: blue;
      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>

Các đơn vị kích thước cột phổ biến

Đơn vịMô tảVí dụ
pxCố định`200px`
%Tỷ lệ container`25%`
frPhần tự do (fraction)`1fr 2fr 1fr` (1:2:1)
autoTự động theo nội dung`auto`
minmax(min, max)Khoảng min-max`minmax(200px, 1fr)`
repeat(n, size)Lặp lại pattern`repeat(3, 1fr)` = `1fr 1fr 1fr`
repeat(auto-fit, ...)Tự động fill (collapse empty)`repeat(auto-fit, minmax(200px, 1fr))`
repeat(auto-fill, ...)Tự động fill (giữ empty track)`repeat(auto-fill, minmax(200px, 1fr))`

Các pattern Grid phổ biến

/ * Holy Grail Layout * /
grid-template-columns: 200px 1fr 200px;        /* Sidebar - Content - Sidebar */

/* Responsive grid tự động */
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

/* Asymmetric layout */
grid-template-columns: 1fr 2fr 1fr 1fr;

/* Fixed + fluid */
grid-template-columns: 300px 1fr minmax(200px, 300px);

/* Named lines (grid lines) */
grid-template-columns: [start] 1fr [middle] 2fr [end];
/* Dùng: grid-column: start / end; */

grid-gap / gap

/* Cũ */
grid-gap: 20px;              /* row-gap + column-gap */
grid-row-gap: 10px;
grid-column-gap: 20px;

/* Mới (CSS Grid Level 2) - khuyến nghị */
gap: 20px;
row-gap: 10px;
column-gap: 20px;

Lưu ý

  • `fr` chỉ phân chia **không gian còn lại** sau khi trừ các track fixed/auto.
  • `auto-fit` vs `auto-fill`: `auto-fit` collapse empty tracks, `auto-fill` giữ track rỗng.
  • Grid items tự động đặt theo thứ tự HTML (auto-placement) trừ khi chỉ định `grid-column/row`.