4

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

1 Answer 1

7

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:

2
  • Thanks Mary, it fixed the problem:). However margin-collapsing still doesn't look right to me in this case as the background applied to body should start 50px down the page, not on the top of it. Don't you think?
    – Alan
    Oct 11, 2014 at 6:56
  • 1
    @Alan - the background on body is a separate issue altogether. In HTML, when no background is defined on the html element, it adopts the background of the body element. The viewport then adopts the background of the html element, turning the whole page red.
    – Alohci
    Oct 11, 2014 at 10:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.