网格布局
弹性布局适合线性排列的场景,对于二维布局(多行多列)更适合使用网格布局
“网格布局”(Grid Layout)是 CSS 中一种强大的二维布局系统,它可以同时在 行(rows) 和 列(columns) 上对元素进行精确控制。相比于 flex(一维布局),grid 更适合用来构建完整的页面结构或复杂组件布局。
网格容器
css
.container {
display: grid; /* 启用网格布局 */
grid-template-columns: 100px 200px auto; /* 定义列宽 */
grid-template-rows: 80px auto 100px; /* 定义行高 */
gap: 10px; /* 行列间距,可分别设置 row-gap / column-gap */
}绘制轨道
grid-template-columns:列轨道
grid-template-rows:行轨道
轨道支持的单位:
| 类型 | 单位 | 含义 | 示例 |
|---|---|---|---|
| 固定长度 | px, em, rem, % | 固定或相对大小 | 100px, 50% |
| 比例单位 | fr | 分配剩余空间的份额 | 1fr, 2fr |
| 内容自适应 | auto, min-content, max-content, fit-content() | 根据内容自适应 | auto, min-content |
| 函数类单位 | minmax(min, max) | 在最小和最大值之间自适应 | minmax(150px, 1fr) |
1️⃣ 固定单位
grid-template-columns: 100px 200px 300px;- 三列,固定宽度;
- 不会随容器变化而自适应。
2️⃣ 百分比单位
grid-template-columns: 50% 50%;- 按容器宽度计算;
- 两列平均分。
3️⃣ fr(fraction)
grid-template-columns: 1fr 2fr 1fr;意思是:网格宽度剩余空间按比例 1:2:1 分配。 所有固定宽度的轨道计算完后,剩余空间由
fr轨道瓜分。
4️⃣ auto
grid-template-columns: 200px auto 100px;- 第1列固定 200px;
- 第2列自动占用剩余内容宽度;
- 第3列固定 100px。
网格间距
在 Grid 中,网格间距 是指「轨道之间的空隙」, 包括:
- 行间距(row-gap)
- 列间距(column-gap)
css
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 100px);
gap: 10px; /* 行列都10px */
}css
row-gap: 10px;
column-gap: 10px;css
gap: 20px 10px; /* 第一个是行间距,第二个是列间距 */