
如何在 div 中保持两个 div 居中并重叠
在同一个 div 容器内拥有两个子 div,要求它们对齐并且重叠。虽然问题描述中提到了“重叠”,但需要澄清一下,是指小 div 位于大 div 之上。
为了实现此效果,我们可以使用 css 定位。首先,为父 div 设置红色边框并使其居中:
.box {
width: 500px;
height: 500px;
border: 5px solid red;
margin: 100px auto;
}然后,为两个子 div 设置绝对定位并使用 left、top、right 和 bottom 值使它们占据父 div 的整个区域:
.inner1,
.inner2 {
width: 200px;
height: 200px;
background: blue;
margin: auto;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}为了使小 div 在大 div 上方,我们可以增加它的宽度和高度:
.inner1 {
width: 400px;
height: 400px;
background: yellow;
}这样,两个 div 就会在父 div 内对齐且重叠,而不会影响父 div 的外观。










