align-self 和 justify-self 仅作用于网格项目,分别控制其在交叉轴和主轴的对齐;仅当父容器为 grid/inline-grid 时生效,Flex 中 justify-self 无效。
align-self 控制单个网格项目在**交叉轴**(cross axis)上的对齐,justify-self 控制其在**主轴**(main axis)上的对齐。它们只对**网格项目**(grid item)生效,不能写在容器上;写在容器上会直接被忽略。
注意:只有当父容器是 display: grid 或 display: inline-grid 时,这两个属性才起作用。Flex 容器中对应的是 align-self(有效)和 justify-self(无效)——后者在 Flex 中完全不支持。
align-self 取值包括:start、end、center、stretch(默认)、self-start、self-end
justify-self 取值类似,但部分浏览器对 left/right 支持有限,推荐优先用 start/end
align-items 或 justify-items(容器级),会被单个项目上的 align-self/justify-self 覆盖最常遇到的情况是:写了 align-self: center 却毫无变化。根本原因通常是——项目没有“可对齐的空间”。
grid-template-rows)或列宽(grid-template-columns),导致轨道尺寸为 auto,项目撑满轨道,stretch 成为唯一可见行为height 或 width 且等于轨道尺寸,失去拉伸/偏移余地grid-area 跨越多行/多列,此时 align-self 仍作用于该单元格区域整体,但视觉上可能被误解为“没动”justify-self 在 rtl 文本方向下的表现有偏差,建议测试时检查 direction 设置place-self 是 align-self 和 justify-self 的简写,语法为 place-self: 。可以混用,但要注意覆盖逻辑:
place-self: center 和 justify-self: start,后者会覆盖简写中的 justify 部分place-self: center stretch
等价于 align-self: center; justify-self: stretch
place-self 又单独写其中一个子属性,容易产生维护困惑/* 推荐:清晰、无歧义 */
.item-a {
align-self: end;
justify-self: center;
}
/ 不推荐:place-self 被部分覆盖,语义模糊 /
.item-b {
place-self: center;
justify-self: start;
}
真正影响最终位置的不只是这两个属性,还有网格轨道本身的尺寸策略和项目的盒模型行为。
align-self: stretch(默认)会让项目填满整个轨道高度,但如果项目设置了 margin: auto,它会优先居中——此时 align-self 失效fr 单位(如 1fr)且内容为空时,轨道高度为 0,align-self: center 无法体现效果justify-self 在 rtl 容器中,start 指向右边界,end 指向左边界,需结合 direction 判断预期minmax(0, 1fr) 替代 1fr 可避免因内容过长导致的溢出挤压,让 align-self 更稳定生效