
如何让 div 中的两个子 div 重叠并在母 div 中居中?
需要在两个子 div 中的一个后面叠放另一个,同时保持它们在母 div 中水平或垂直居中,而不会影响母 div 的外观或超出母 div 的边界。
css 实现
- 将母 div 定位为相对定位(position: relative)。
- 将子 div 定位为绝对定位(position: absolute)以将它们从正常流中移除。
- 使用 left, top, right, bottom 属性将子 div 居中。
- 设置子 div 的 margin 为 auto 以将其余白设置为其两侧的所有可用空间的平均值。
示例代码
.box {
width: 500px;
height: 500px;
border: 5px solid red;
margin: 100px auto;
position: relative;
}
.inner1,
.inner2 {
width: 200px;
height: 200px;
background: blue;
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
.inner1 {
width: 400px;
height: 400px;
background: yellow;
}结果:
在母 div 中重叠的两个子 div,较小的 div 叠放在较大的 div 上方,并且两者在水平和垂直方向上都居中。










