Strange extra distance between title and body when adding extra element

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 show extra extra space at the top of the screen, as well as a scroll bar.

Removing the h2 element makes this space disappear.

My question is: what is happening? Is there an HTML layout rule that explains why space is being added?

+4
source share
3 answers

This is one of the cases of a stranger turning a margin - two elements of the block level, vertical fields will always collapse in a normal flow. The two elements in this case are <body> and <h2> . If you remove <h2> from the normal flow (float, absolutely position) or change its display to inline-block , you will see that the fields will not be destroyed and will be "respected" using <body>

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

From 2.1 Spec :

"If the fields of an element are collapsed with the top edge of the parent, the top border edge of the field will be the same as the parent."

This explains why the upper border on <h2> adds a space on <body> - as mentioned earlier, if you had to swim, absolutely position or change to display: inline-block; the edge of the upper edge <h2> will be the same as the border with the parents, and the “space” will disappear:

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

+7
source

This problem is indicated as collapsing fields

To fix, add:

  h2 { padding: 0; margin: 0; } 

And the problem has disappeared.

Another solution would be to add float: left or display: inline-block in h2

Working script

+1
source

This is because your <header> element appears as a floating element. By default, a block-level element expands horizontally to fill the entire parent container, and also extends beyond any floating content .

The <h2> element of the block level actually starts to clear at the point 0,0 in the upper left corner of the screen and from there it puts a default edge to it to bring the text down. Then your floating <header> element starts from this field to start from a new text position, as shown below:

Inspecting the element's dimensions

An easy way around this is to use a space instead of fields (if you need space above <h2> but not above everything). See the jsFiddle example.

+1
source

All Articles