如何在 div 中居中并重叠 div?
在单个 div 内放置两个子 div 时,常常有让它们在水平和垂直方向上居中的需求,同时保留子 div 相对父 div 的重叠部分。
css 解决方案
通过 css 样式,可以轻松实现上述要求:
设置父 div:
.parent-div { width: 500px; height: 500px; border: 5px solid red; margin: 100px auto; position: relative; }
设置子 div:
.child-div1, .child-div2 { width: 200px; height: 200px; background: blue; margin: auto; position: absolute; left: 0; top: 0; right: 0; bottom: 0; } .child-div1 { width: 400px; height: 400px; background: yellow; }
这样的 css 样式可以使两个子 div 在父 div 中重叠并居中,同时不影响父 div 的外观或溢出父 div。