默认 justify-self 和 align-self 为 stretch(撑满),设为 center 则居中;二者互斥,需确保行/列轨道有明确空间,place-self 可简写为 place-self: center 或 place-self: center stretch。
默认情况下,grid item 会拉伸(stretch)填满所在网格区域的宽高;设为 center 则居中对齐,不拉伸。关键看你要的是「撑满」还是「居中显示」——二者互斥,不能同时生效。
justify-self: stretch 水平方向填满列轨道(忽略自身 width)align-self: stretch 垂直方向填满行轨道(忽略自身 height)justify-self: center 水平居中,宽度保持内容或显式设置值align-self: center 垂直居中,高度同理align-items: stretch(默认),子项又没设 align-self,就会继承 stretch 行为常见原因是父 grid 容器的行高(grid-template-rows)设成了 auto 或内容高度,导致没有“可居中的空间”。center 需要明确的可用空间才能生效。
grid-template-rows: 100px 1fr,而不是全用 auto
min-height / height 等样式限制了 item 自身高度,干扰了居中计算display: contents 或 visibility: hidden,align-self 会失效align-self: center 在 grid-template-rows: auto 下的支持较保守,Chrome 更宽松不能。这两个属性控制的是整个网格轨道(grid tracks)在容器内的分布,不是单个 item 的位置。它们只在网格容器有额外空间(比如容器比所有行/列加起来还大)时才起作用。
justify-content: center → 所有列轨道整体水平居中(留白均分左右)align-content: center → 所有行轨道整体垂直居中(留白均分上下)
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 是 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 可能解析异常,上线前建议验证。