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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With