默认 justify-self 和 align-self 为 stretch(撑满),设为 center 则居中;二者互斥,需确保行/列轨道有明确空间,place-self 可简写为 place-self: center 或 place-self: center stretch。

grid-item 的 justify-self 和 align-self 怎么选 stretch 还是 center
默认情况下,grid item 会拉伸(stretch)填满所在网格区域的宽高;设为 center 则居中对齐,不拉伸。关键看你要的是「撑满」还是「居中显示」——二者互斥,不能同时生效。
-
justify-self: stretch水平方向填满列轨道(忽略自身 width) -
align-self: stretch垂直方向填满行轨道(忽略自身 height) -
justify-self: center水平居中,宽度保持内容或显式设置值 -
align-self: center垂直居中,高度同理 - 若父容器设置了
align-items: stretch(默认),子项又没设align-self,就会继承 stretch 行为
为什么设置了 align-self: center 却没效果
常见原因是父 grid 容器的行高(grid-template-rows)设成了 auto 或内容高度,导致没有“可居中的空间”。center 需要明确的可用空间才能生效。
- 确保行轨道有固定高度,比如
grid-template-rows: 100px 1fr,而不是全用auto - 检查是否被
min-height/height等样式限制了 item 自身高度,干扰了居中计算 - 如果用了
display: contents或visibility: hidden,align-self会失效 - 注意:Firefox 对
align-self: center在grid-template-rows: auto下的支持较保守,Chrome 更宽松
justify-content 和 align-content 能不能替代 item 级对齐
不能。这两个属性控制的是整个网格轨道(grid tracks)在容器内的分布,不是单个 item 的位置。它们只在网格容器有额外空间(比如容器比所有行/列加起来还大)时才起作用。
-
justify-content: center→ 所有列轨道整体水平居中(留白均分左右) -
align-content: center→ 所有行轨道整体垂直居中(留白均分上下) - 它们不影响 item 在自己格子内的对齐方式,item 仍由
justify-self/align-self或全局justify-items/align-items控制 - 若只有一行一列轨道,
align-content永远无效(无“多行”可对齐)
.container {
display: grid;
grid-template-columns: 100px 1fr;
grid-template-rows: 80px 1fr; /* 固定首行,给第二行留出居中空间 */
height: 300px;
}
.item {
justify-self: center;
align-self: center;
background: #eee;
}用 place-self 一次性写两个方向对齐
place-self 是 align-self 和 justify-self 的简写,顺序固定为「垂直方向 值 水平方向 值」,和 margin 类似。
立即学习“前端免费学习笔记(深入)”;
-
place-self: center;等价于align-self: center; justify-self: center; -
place-self: center stretch;→ 垂直居中、水平拉伸 -
place-self: stretch center;→ 垂直拉伸、水平居中(注意顺序!) - 不支持单值缩写如
place-self: center center,会报错;必须按「align justify」顺序写两个值或一个值(表示两边相同)
浏览器对 place-self 支持良好(Chrome 57+、Firefox 52+、Safari 10.1+),但旧版 Safari 可能解析异常,上线前建议验证。










