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

如何用CSS实现父div内两个子div居中且重叠显示?

容器 child 居中 个子 207    来源:    2025-03-21

要实现父 div 内两个子 div 居中且重叠显示,可以使用以下 CSS 方法:

HTML 结构

<div class="parent">
  <div class="child child1">Child 1</div>
  <div class="child child2">Child 2</div>
</div>

CSS 样式

.parent {
  position: relative; /* 父容器设置为相对定位 */
  width: 300px; /* 父容器的宽度 */
  height: 200px; /* 父容器的高度 */
  background-color: #f0f0f0; /* 父容器的背景色 */
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.child {
  position: absolute; /* 子容器设置为绝对定位 */
  width: 100px; /* 子容器的宽度 */
  height: 100px; /* 子容器的高度 */
  background-color: #ccc; /* 子容器的背景色 */
  display: flex; /* 使用 Flexbox 布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.child1 {
  background-color: #ffcc00; /* 第一个子容器的背景色 */
}

.child2 {
  background-color: #00ccff; /* 第二个子容器的背景色 */
}

解释

  1. 父容器 (parent):

    • 使用 position: relative; 使得子容器的绝对定位相对于父容器进行定位。
    • 使用 display: flex; 结合 justify-content: center;align-items: center; 使得子容器在父容器中水平和垂直居中。
  2. 子容器 (child):

    • 使用 position: absolute; 使得子容器可以重叠显示。
    • 使用 display: flex; 结合 justify-content: center;align-items: center; 使得子容器内的内容居中显示。
  3. 子容器样式 (child1child2):

    • 分别设置不同的背景色以便区分两个子容器。

结果

  • 两个子 div 会在父 div 中居中显示,并且重叠在一起。
  • 你可以通过调整 z-index 属性来控制哪个子 div 显示在上层。

例如,如果你想让 child2 显示在 child1 的上层,可以添加以下样式:

.child2 {
  z-index: 2; /* 设置较高的 z-index 值 */
}

.child1 {
  z-index: 1; /* 设置较低的 z-index 值 */
}

这样,child2 就会显示在 child1 的上层。