配了多年 Grid 布局,每次居中都要写两行 align-items 加 justify-items——今天 Safari TP 28 用一个属性把它彻底原生化了

写 Grid 布局时让内容上下左右居中,你大概率这样写过:

.container {
  display: grid;
  align-items: center;
  justify-items: center;
}

两行,一行管竖轴,一行管横轴。没问题,但每次都要写两个属性这件事本身就很烦。

Safari Technology Preview 28 把这件事用一个属性收了:

.container {
  display: grid;
  place-items: center;
}

一行,等价于上面两行。

怎么记

place-items 是 align-items 和 justify-items 的简写。记不住顺序的话想一下:先竖后横——对应 block 方向优先,inline 方向其次,和 Flexbox 的 place-content、place-self 家族一致。

单个值时两个方向同时生效,place-items: center 等于 align-items: center; justify-items: center。

两个值时第一个给 align-items,第二个给 justify-items:place-items: start center 等于竖轴顶部对齐、横轴居中。

实际例子

卡片网格,每个格子里的内容都要居中:

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  place-items: stretch; /* 默认值,等于 align-items + justify-items 均为 stretch */
}

/* 某个特定卡片要居中?直接覆盖 */
.card-grid.centered {
  place-items: center;
}

一个小坑:Flexbox 场景

place-items 在 Flexbox 容器上也会生效,但 justify-items 在 Flexbox 场景下本身就没意义(Flex 项目沿主轴的分布由 justify-content 控制,不是 justify-items)。所以如果你在 flex 容器上写了 place-items: center end,第二个值会被浏览器静默忽略,只生效 align-items: center。

.flex-container {
  display: flex;
  place-items: center end; /* justify-items 的 end 被忽略,只有 align-items: center 生效 */
}

如果你想同时控制 Flex 主轴和交叉轴,还是要用 align-items + justify-content 组合。

现在能用吗

根据 caniuse 数据:place-items 在 Chrome 59+、Firefox 45+、Safari 11+、Edge 79+ 已广泛支持。这个属性本身并不新——Safari TP 28 的更新是把它正式纳入 WebKit 最新特性列表,说明 Apple 在持续补齐 CSS 盒模型对齐的完整实现。

如果你在写这两年内的项目,直接用没有任何问题。旧项目如果还在兼容 IE,这个属性就别用了。

下一步

下次写 Grid 布局需要对齐时,先想一下 place-items 能不能搞定,再决定要不要拆成 align-items + justify-items 两行。这个习惯能省不少打字量。

附:常见简写家族 place-items / place-content / place-self,都是先竖后横,记住一个就能推其他。

评论区

0 条评论

登录后可评论。

阿速·性能优化 2276 阅读