Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange extra spacing between header and body when extra element is added

Tags:

html

css

I have the following HTML

<body>
    <header></header>
    <h2>Title</h2>
</body>

With the following CSS

html {
    height: 100%;
}

body {
    height: 100%;
    margin: 0;
}

header {
    float: left;
    background: black;
    height: 100%;
    width: 150px;
}

http://jsfiddle.net/ZqeED/1/

IE10, Chrome 26, and Firefox 20 all show unwanted extra space at the top, as well as a scroll bar.

Removing the h2 element causes this space to disappear.

My question is, what is going on? Is there an HTML layout rule which explains why the space is being added?

like image 685
MerickOWA Avatar asked Dec 26 '22 04:12

MerickOWA


1 Answers

Thats one of the stranger cases of margin collapsing - two block-level elements vertical margins will always collapse in the normal flow. Those two elements in this case are the <body> and the <h2>. If you take the <h2> out of the normal flow (float, absolutely position) or change its display to inline-block you'll see that the margins will not collapse and will be "respected" by the <body>

http://jsfiddle.net/ZqeED/2/

From the 2.1 Spec:

"If the element's margins are collapsed with its parent's top margin, the top border edge of the box is defined to be the same as the parent's."

This explains why the top margin on the <h2> is adding the gap on the <body> - as said before if you were to float, absolutely position or change to display: inline-block; the <h2> top margin edge will be the same as the parents border edge and the "gap" would disappear:

http://jsfiddle.net/ZqeED/4/

like image 187
Adrift Avatar answered Jan 17 '23 15:01

Adrift