
容器内两子元素居中重合
如何在一个容器 div 内居中对齐两个子 div 并使其重叠?要求不影响父 div 外观或溢出容器外。
解决方案
实现该效果需要使用 CSS 的绝对定位和相对定位。以下是一个示例代码:
HTML:
CSS:
.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 使用 position: relative 使其成为相对定位元素。
- 对子 div 使用 position: absolute 使子 div 相对于父 div 定位。
- 使用 left, top, right 和 bottom 属性将子 div 设置为在父 div 中拉伸。
- 使用 margin: auto 设置子 div 在其各自轴上的居中位置。
- 通过增加较小的子 div 的大小并在其上应用不同背景色来实现重叠效果。










