You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CSS Grid容器中使多个元素垂直水平居中且层叠放置?

实现CSS Grid中两个子元素重叠并居中的方法

当然可以实现,核心是让两个子元素占据Grid容器的同一个网格单元格,同时确保它们都水平垂直居中。

你原来的代码只设置了垂直方向的align-self,没处理水平居中,而且默认情况下Grid会将每个子元素分配到独立的网格单元,所以两个元素不会重叠。

解决方案步骤:

  • 给Grid容器添加place-items: center,这个属性可以同时统一设置所有子元素的垂直和水平居中,比单独给每个元素写align-self和justify-self更高效。
  • 给两个子元素都设置grid-area: 1 / 1,强制它们都占据第一行第一列的网格单元,这样第二个元素就会自然覆盖在第一个元素上方。

修改后的完整代码:

<div
  style="
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
    height: 200px;
    width: 200px;
    background-color: blue;
    place-items: center;
  "
>
  <div
    style="
      width: 100px;
      height: 100px;
      background-color: red;
      grid-area: 1 / 1;
    "
  ></div>
  <div
    style="
      width: 50px;
      height: 50px;
      background-color: yellow;
      grid-area: 1 / 1;
    "
  ></div>
</div>

补充说明:

如果不想用容器级的place-items,也可以给每个子元素单独设置align-self: center; justify-self: center,效果完全一致。另外,若需要调整元素的覆盖层级,可以使用z-index属性控制。

内容的提问来源于stack exchange,提问作者Ole

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:20:23