我正在尝试用另一个具有不同背景的div来包装一个名为content
的div。
但是,当使用带有content
div的“margin-top”时,看起来包装DIV会获得margin-top而不是content
div。
代码:
<!DOCTYPE html>
<html>
<head>
<style>
html {
background-color:red;
}
#container-top {
background-color: #ccc;
overflow: hidden;
padding-top: 10px;
border-bottom: 1px solid #000;
height:30px;
}
#container-bottom {
background-color: #F1F4F2;
}
#content {
margin-top:20px;
}
</style>
</head>
<body>
<div id="container-top">
</div>
<div id="container-bottom">
<div id="content">
Hello
</div>
</div>
</body>
</html>
因此,在示例中,div container-bottom
获取margin-top而不是content
div。
我发现如果我在container-bottom
中添加一个字符,就可以解决问题。
<div id="container-bottom">
**A**
<div id="content">
Hello
</div>
但当然这不是一个好的解决方案......
谢谢,
乔尔
答案 0 :(得分:5)
正在发生的事情称为 保证金折叠 。
如果2个元素的两个边距(顶部和底部,仅右边或左边)正在触摸(或者在你的情况下,内部div的顶部边缘接触外部div的顶部边缘),使用它们之间的最大值(在您的情况下为max(0,20)= 20)并尽可能远离触摸元素(在您的情况下位于容器div(最外面的元素)之外)。
要打破此行为,您必须在2个边距之间放置一些内容 - &gt;容器div顶部的填充可以。
#container-bottom {
background-color: #F1F4F2;
padding-top: 1px;
}
#content {
margin-top:19px;
}
你可以简单地在容器div中放置一个20 px的填充顶部:
#container-bottom {
background-color: #F1F4F2;
padding-top: 20px;
}
#content {
}
有关更多信息,此页面非常好地解释了这一点:Margin Collapsing
答案 1 :(得分:3)
您可以尝试在#container-bottom:
中添加一个不间断的空格<div id="container-bottom">
<div id="content">
Hello
</div>
</div>
这是一个合适的解决方案,因为它经常用于让浏览器知道元素不为空(某些浏览器忽略空元素)。
答案 2 :(得分:1)
Margin-top因其崩塌属性而成为一种神秘生物。我发现解决这个问题的最简单方法是将1px填充顶部应用于容器底部div并将内容margin-top更改为19px。