Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

margin

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 :).

like image 430
Alan Avatar asked Oct 27 '25 23:10

Alan


1 Answers

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
like image 165
Anonymous Avatar answered Oct 30 '25 17:10

Anonymous



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!