html:
<div class="outside">
<div class="inside">
</div>
</div>
我有两个 CSS:#1 和 #2
/*CSS#1 does not work*/
.outside{
background: blue;
width: 400px;
height: 400px;
}
.inside{
background: red;
width: 200px;
height: 200px;
position: relative;
top: 50%;
margin: 0 auto;
margin-top: -100px; /*half height of this div*/
}
/*CSS#2 works well */
.outside{
border: 1px solid black;
width: 400px;
height: 400px;
}
.inside{
background: red;
width: 200px;
height: 200px;
position: relative;
top: 50%;
margin: 0 auto;
margin-top: -100px; /*half height of this div*/
}
我的目标是将“内部”div 放置在“外部”div 的中心(垂直和水平)。我有很多方法可以实现这个目标,但是在这个过程中我发现了一些奇怪的事情。
我发现 CSS#2 工作得很好,但 CSS#1 不工作:当设置 'inside' div 'margin-top: -100px' 时,'outside' 也向上移动..
这是 demo
所以我想知道为什么“边框”在这里效果很好,为什么“背景”不起作用?
最佳答案
您需要添加 overflow: auto;
到那里的父元素,但是你的方法是不正确的,你需要 position
你的子元素 absolute
到父元素而不是 relative
/p>
使用 overflow: auto;
或 border
将解决您的问题,因为它会阻止 collapsing父边距
。
关于html - 为 div 添加边框时出现奇怪的位置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626211/