Skip to content

绘制网格

在grid布局中,绘制网格非常灵活。

警告

grid-template-columns一旦确定,所有行共享同一套列宽**

指定比例

css
.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr
  grid-template-rows:1fr 2fr 1fr
}

重复绘制网格结构

css
.container {
  display: grid;
  grid-template-columns: repeat(3, 100px); /* 定义3列,每列宽度100px */
  grid-template-rows: repeat(2, 100px); /* 定义2行,每行高度为100px */
}

列轨道自动填充

auto-fillauto-fit 都用于 repeat() 中,让 grid 自动创建尽可能多的轨道,但它们在“空轨道的处理方式”上有关键区别。

危险

auto-fill/fit 只能用于 grid-template-columns不能用于 grid-template-rows。这是 CSS Grid 的固有设计限制。

html
<div class="container-fill">
  <div class="item">1</div>
  <div class="item">2</div>
</div>

<div class="container-fit">
  <div class="item">1</div>
  <div class="item">2</div>
</div>
css
.container-fill, .container-fit {
  display: grid;
  gap: 10px;
  width: 520px;      /* 明确宽度:5列 × 100px + 4个gap = 520px */
  border: 3px solid #333;
  margin-bottom: 20px;
  padding: 10px;
}

/* 项目样式 */
.item {
  background: #4CAF50;
  color: white;
  padding: 20px;
  text-align: center;
  font-size: 24px;
}

auto-fill

哪怕没内容也会保留空轨道

css
grid-template-columns: repeat(auto-fill, 100px);

网格有五列,有3列空轨道

css
[item1][item2][empty][empty][empty]

auto-fit:

自动折叠(删除)空轨道,

css
grid-template-columns: repeat(auto-fit, 100px);

网格只有两列,有0列空轨道

css
[item1][item2]
  • 如果容器1000px,则每行最多10个,如果少于10个,卡片宽度将>100px并均分剩余空间

提示

该样式是作为响应式卡片的关键语句,不需要媒体查询就能实现响应式布局

响应式列轨道宽度

repeat(auto-fit, minmax(100px, 1fr))

minmax(100px, 1fr)函数让轨道在绘制时宽度具备响应式。在最小宽度100px上可以均分剩余空间实现item的拉伸

css
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  • 每个卡片最小 100px
  • 空轨道被折叠,item将均分剩余空间

  • item <5
css
/*2个item*/
[260px][260px]
  • item>5
第1行item1item2item3item4item5
第2行item6item7(空)(空)(空)

repeat(auto-fill, minmax(100px, 1fr))

不管item数量是多少,都不会改变列轨道的表现,因此常用该样式设计响应式卡片

剩余空间=容器宽-100*一行最大数量。因此剩余空间必定是<100px,剩余空间将被item均分