Unexpected <body> body behaviour as it's pushed down by child's margin-top [duplicate]

我们两清 提交于 2019-12-22 17:29:13

问题


HTML problems always look so simple that I nearly feel embarassed asking them. But let it be, I have no idea why this is happening.

In this fiddle http://jsfiddle.net/o5ee1oag/2/ body is being pushed down by header's margin(50px):

<body>
 <div id="background"></div>
 <header>
  <ul>
   <li>Button 1</li>
   <li>Button 2</li>
  </ul>
 </header>
</body>

In consequence div#background { position: absolute; } is being pushed down too. Then I go to Firebug, apply background: red; to the body and the whole area gets red, with margin included.

1) Why is this happening, the body is 50px from the top?

2) How do I prevent body from being pushed down?

Thanks :).


回答1:


Add display: inline-block; to header

JSFiddle - DEMO

header {
    display: inline-block;
    width:100%;
    height:100px;
    margin-top:50px;
    background:rgba(0, 0, 0, 0.4);
}

The issue is happening because of the margin collapsing:

Your header element is next to the body that have top margin 50px and the margin combine and are applied to the body and this forces the body's content to start below (50px) the applied collapsed margin in compliance with the box model.

The div#background have position: absolute; and the absolutely positioned boxes can have margins but they do not collapse with any other margins, If you remove the position: absolute; from div#background then the margin is applied to header and don't collapsed with the body - DEMO

OR: You could also add top: 0px; to the div#background - DEMO

Margin collapsing spec:

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing. - by Mozilla MDN

Read More about collapsing margins behavior:

  • W3.ORG - 8.3.1 Collapsing margins
  • Sitepoint - Collapsing Margins


来源:https://stackoverflow.com/questions/26311891/unexpected-body-body-behaviour-as-its-pushed-down-by-childs-margin-top

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!