保证金顶部向下推外部
我有一个标题div作为我的包装div中的第一个元素,但是当我添加顶部边距到头部div内的h1时,它会将整个标题div推下。 我意识到这种情况发生时,我应用顶部边距到页面上的第一个可见元素。
这是一个示例代码片段。 谢谢!
div#header{ width: 100%; background-color: #eee; position: relative; } div#header h1{ text-align: center; width: 375px; height: 50px; margin: 50px auto; font-size: 220%; background: url('../..http://img.dovov.comname_logo.png') no-repeat; }  <div id="header"> <h1>Title</h1> <ul id="navbar"></ul> </div> 
 把overflow:auto在父div 
  在这个链接看到更多 
 我没有一个坚实的解释,为什么发生这种情况,但我已经解决了这个问题,通过改变top-margin到top-padding ,或者添加display: inline-block到元素样式。 
编辑:这是我的理论
我有一种感觉,这与利润如何崩溃(合并)有关。
来自W3C Collapsing Margins :
在本说明书中,expression式的折叠边界意味着两个或多个盒子(可以彼此相邻或嵌套)的相邻边界(没有非空内容,填充或边界区域或间隔将它们分开)组合以形成单个边界。
我的理论是,由于你的第一个元素在身体旁边,所以两个边界相结合并应用到身体上:这就迫使身体的内容在符合盒子模型的情况下开始低于应用的塌陷边缘。
有些情况下,利润率不会下降,这可能值得玩弄(来自Collapsing Margins ):
 * floated elements * absolutely positioned elements * inline-block elements * elements with overflow set to anything other than visible (They do not collapse margins with their children.) * cleared elements (They do not collapse their top margins with their parent block's bottom margin.) * the root element 
这是避免亲子元素之间的边缘折叠的一些方法。 使用一个更适合您的样式的其余部分:
-  将display设定为block以外的block。
-  将float设置为none。
-  删除边距,并使用padding。 例如,如果您有margin-top: 10px,请用padding-top: 10px;replace为padding-top: 10px;。
-  删除边距,并使用属性top,bottom等position(absolute或relative)。例如,如果你有margin-top: 10px,replace为position: relative; top: 10px;position: relative; top: 10px;。
-  在边距正在折叠的一侧添加padding或border到父元素。 边框可以是1px并且是透明的。
-  将overflow设置为对父元素visible的以外。
  display: flex将在这种情况下工作。 给父元素display: flex; 然后按照您的要求为h1标签分配保证金。 
今天遇到这个问题。
  overflow: hidden当我有更多的元素后, overflow: hidden没有按预期工作。 
 所以我试图改变父div的显示属性和display: flex工作! 
希望这可以帮助某人。 🙂
在父元素顶部添加一点填充可以解决这个问题。
 .parent{ padding-top: 0.01em; }