插件窝 干货文章 如何用CSS实现父容器中两个子div的居中重叠显示?

如何用CSS实现父容器中两个子div的居中重叠显示?

居中 容器 元素 position 938    来源:    2025-03-19

要实现父容器中两个子 div 的居中重叠显示,可以使用 CSS 的 position 属性和 flexbox 布局。以下是具体的实现步骤:

1. 使用 flexbox 实现居中

首先,将父容器设置为 flex 布局,并使用 justify-contentalign-items 属性将子元素居中。

2. 使用 position: absolute 实现重叠

然后,将两个子 div 设置为 position: absolute,这样它们就可以重叠在一起。

示例代码

<div class="parent">
  <div class="child1">子元素1</div>
  <div class="child2">子元素2</div>
</div>
.parent {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  position: relative; /* 父容器设置为相对定位 */
  width: 300px; /* 父容器宽度 */
  height: 200px; /* 父容器高度 */
  border: 1px solid #000; /* 边框,方便查看 */
}

.child1, .child2 {
  position: absolute; /* 子元素设置为绝对定位 */
  top: 50%; /* 垂直居中 */
  left: 50%; /* 水平居中 */
  transform: translate(-50%, -50%); /* 精确居中 */
}

.child1 {
  background-color: rgba(255, 0, 0, 0.5); /* 半透明红色背景 */
  width: 150px;
  height: 100px;
}

.child2 {
  background-color: rgba(0, 0, 255, 0.5); /* 半透明蓝色背景 */
  width: 100px;
  height: 150px;
}

解释

  1. 父容器 (parent):

    • display: flex; 将父容器设置为 flex 布局。
    • justify-content: center;align-items: center; 将子元素在水平和垂直方向上居中。
    • position: relative; 使得子元素的 position: absolute; 相对于父容器定位。
  2. 子元素 (child1child2):

    • position: absolute; 使得子元素可以重叠。
    • top: 50%;left: 50%; 将子元素的左上角定位到父容器的中心。
    • transform: translate(-50%, -50%); 将子元素的中心点移动到父容器的中心,从而实现精确居中。

结果

  • 两个子 div 会在父容器的中心重叠显示。
  • 你可以通过调整 z-index 属性来控制哪个子元素在上层显示。

进一步调整

如果你希望其中一个子元素在上层显示,可以为其设置 z-index 属性:

.child1 {
  z-index: 1; /* 使 child1 在上层显示 */
}

这样,child1 就会覆盖在 child2 之上。