justify-items 控制网格项在行轴的对齐,align-items 控制列轴对齐,默认均为 stretch;通过设置 justify-items: center 和 align-items: center 可实现单元格内容水平垂直居中;可配合 justify-self 和 align-self 对特定子项进行局部调整,如表头左对齐而其他内容居中;注意父容器需设置 display: grid,避免固定尺寸影响拉伸效果,并处理图片的 vertical-align 问题;在卡片布局中,结合 align-items 与内部 flex 布局可实现标题居上、按钮居底的自然分布。
在使用 CSS Grid 布局时,justify-items 和 align-items 是控制网格单元格内容对齐的关键属性。合理组合它们,可以让布局更整齐、响应更自然。
理解 justify-items 与 align-items 的作用方向
justify-items 控制网格项在行轴(横轴)上的对齐方式,而 align-items 控制在列轴(纵轴)上的对齐。这类似于 Flexbox 中的 justify-content 与 align-items,但作用于每个单元格内部。
- justify-items:start、end、center、stretch(默认)
- align-items:start、end、center、stretch(默认)
例如,一个网格容器设置了:
display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 100px 100px;
此时所有子项默认被拉伸填满单元格(stretch)。若想让所有项目居中显示,只需:
立即学习“前端免费学习笔记(深入)”;
justify-items: center; align-items: center;
这样每个单元格内的内容都会水平垂直居中。
与 justify-self / align-self 配合实现局部调整
当大多数单元格采用统一对齐,但个别需要特殊处理时,可在特定子元素上使用 justify-self 或 align-self 覆盖父容器设置。
比如表格头部需要左对齐,其他数据居中:
.grid-container { display: grid; justify-items: center; align-items: center; } .header-cell { justify-self: start; /* 覆盖水平对齐 */ }
这样既保持整体一致性,又保留灵活性。
避免常见对齐问题的小技巧
- 如果发现内容没有对齐预期位置,先检查是否设置了
display: grid
在父容器上。 - 注意
stretch
是默认值,若子元素有固定尺寸(如 width/height),可能无法完全拉伸。 - 图片或内联元素在单元格中可能受 vertical-align 影响,建议设为块级元素或使用 object-fit。
实用场景示例:卡片网格布局
设计一组等高卡片,标题居中、按钮底部对齐:
.card-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; align-items: start; /* 内容顶部对齐 */ } .card { display: flex; flex-direction: column; justify-content: space-between; height: 100%; } /* 利用 align-items: start + flex 子结构实现自然分布 */
这里虽然没直接用 justify-items,但结合 align-items 控制整体起点,再由内部 flex 完成细节分布,是常用模式。
基本上就这些。掌握这两个属性的组合逻辑,能大幅提升 Grid 布局的整洁度和开发效率。不复杂但容易忽略。