William Wettersten
William Wettersten

Reputation: 117

Webkit Extra Space at the top of the 'body' element when setting a margin-top on a descendant element

I was playing around with making my page occupy the full viewport with this basic

html {
  height: 100%;
}

body {
  min-height: 100%;
}

but I noticed that when I added a block element with a margin, the page sizing was off by the amount of the margin. To demonstrate, try this html in a webkit browser:

<html style="height: 100%; margin: 0; padding: 0;">
  <body style="min-height: 100%; margin: 0; padding: 0;">
    <h1 style="margin-top: 100px;">Box Sizing</h1>
  </body>
</html>

You will notice that the body always overflows the html element, causing it to scroll. Does anybody know why this is overflowing?

Upvotes: 1

Views: 42

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240878

This is known as collapsing margins. The vertical margin on the h1 element is collapsing with the body element, which causes the adjoining margins to combime and form a single margin, thereby resulting in the body element being shifted down (as though it has a margin-top of 100px.

According to section 8.3.1 of the relevant spec, the following rule(s) prevent the margins from collapsing:

Margins of inline-block boxes do not collapse (not even with their in-flow children).

Therefore you could simply set the display of the element to inline-block and then add width: 100%. You could also float the element as well:

Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).

In the updated example below, I simply set the display of the h1 element to inline-block so that the margins no longer collapse.

html {
  height: 100%;
}
body {
  min-height: 100%;
  margin: 0;
}
h1 {
  margin-top: 100px;
  display: inline-block;
  width: 100%;
}
<h1>Box Sizing</h1>

See the spec I linked to for a more detailed explanation along with additional workarounds and rules that prevent the margins from collapsing.

Upvotes: 1

Related Questions