在css grid布局中,align-content和justify-content都用于调整网格轨道在整个容器内的对齐方式,但作用方向不同。justify-content处理行轴方向,align-content处理列轴方向。只有当容器尺寸大于网格内容总尺寸时,这两个属性才会产生可见效果。

基础概念说明
网格容器存在两条轴:水平的主轴与垂直的-cross轴。justify-content决定网格轨道块在主轴上的位置,align-content决定其在交叉轴上的位置。常见取值有:
- start:靠起始位置
- center:居中
- end:靠结束位置
- space-between:两端对齐,中间平分
- space-around:每侧间隔相等
- stretch:拉伸填满(默认值)
结合使用的写法
我们可以在同一个容器上同时声明两个属性,让内容在水平和垂直方向都居中:
.container {
display: grid;
grid-template-columns: 100px 100px;
grid-template-rows: 80px 80px;
width: 400px;
height: 300px;
/* 水平居中 */
justify-content: center;
/* 垂直居中 */
align-content: center;
border: 1px solid #ccc;
}
不同组合的效果对比
下面用表格列出几种常见组合的表现:
| justify-content | align-content | 视觉效果 |
|---|---|---|
| start | start | 内容贴在左上角 |
| center | center | 内容在正中央 |
| space-between | center | 水平两端分布,垂直居中 |
| end | end | 内容贴在右下角 |
代码示例:水平垂直居中布局
以下完整示例展示如何结合两者让网格整体居中:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<style>
.box {
display: grid;
grid-template-columns: 60px 60px;
grid-template-rows: 60px 60px;
width: 300px;
height: 200px;
justify-content: center;
align-content: center;
background: #f0f0f0;
}
.item {
background: #409eff;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div class="box">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
</body>
</html>
使用注意点
如果网格轨道已经通过grid-template或fr单位填满了容器,那么align-content和justify-content的start、center等取值将看不出变化,因为此时没有多余空间。只有在容器明显大于内容总尺寸,或使用了固定像素轨道时,结合使用才有意义。合理搭配这两个属性,可以替代不少传统需要用外层flex包裹才能实现的居中方案。
css_gridalign-contentjustify-content修改时间:2026-07-29 20:48:19