要实现父 div
内两个子 div
居中且重叠显示,可以使用以下 CSS 方法:
<div class="parent">
<div class="child child1">Child 1</div>
<div class="child child2">Child 2</div>
</div>
.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; /* 第二个子容器的背景色 */
}
父容器 (parent
):
position: relative;
使得子容器的绝对定位相对于父容器进行定位。display: flex;
结合 justify-content: center;
和 align-items: center;
使得子容器在父容器中水平和垂直居中。子容器 (child
):
position: absolute;
使得子容器可以重叠显示。display: flex;
结合 justify-content: center;
和 align-items: center;
使得子容器内的内容居中显示。子容器样式 (child1
和 child2
):
div
会在父 div
中居中显示,并且重叠在一起。z-index
属性来控制哪个子 div
显示在上层。例如,如果你想让 child2
显示在 child1
的上层,可以添加以下样式:
.child2 {
z-index: 2; /* 设置较高的 z-index 值 */
}
.child1 {
z-index: 1; /* 设置较低的 z-index 值 */
}
这样,child2
就会显示在 child1
的上层。