Why is there white space above the header?

I set no margin or padding at all, but there is white space above the header.

<header style="background-color:gray">
  <h1>Test margin collapsing</h1>

There is no margin in the "header" or "h1". So why?

First of all, the browser adds margin to "h1". Open your developer console, you can see things like "-webkit-margin-before: 0.67em;"

So there should be space between "h1" and its parent, the "header". But how come the margin shows on top of the header?

That’s because of "margin collapsing". As said on MDN website, "If there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of its first child block, then those margins collapse". And what’s more surprising, " The collapsed margin ends up outside the parent. "

How to fix it? Just add a padding to the parent:

    <header  style="background-color: gray; padding: 1px">
		<h1 >Test margin collapsing</h1>

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.