Margin-Top push outer div down
I have a header div as the first element in my wrapper div, but when I add a top margin to a h1 inside the header div it pushes the entire header div down. I realize this happens whenever I apply a top margin to the first visible element on a page.
Here is a sample code snippet. Thanks!
div#header{
width: 100%;
background-color: #eee;
position: relative;
}
div#header h1{
text-align: center;
width: 375px;
height: 50px;
margin: 50px auto;
font-size: 220%;
background: url('../../images/name_logo.png') no-repeat;
}
<div id="header">
<h1>Title</h1>
<ul id="navbar"></ul>
</div>
Solution 1:
put overflow:auto
in the parent div
see more in this link
Solution 2:
I don't have a solid explanation on why this happens, but I've fixed this by changing the top-margin
to top-padding
, or adding display: inline-block
to the element style.
EDIT: This is my theory
I have a feeling it has something to do with how margins are collapsed (combined).
from W3C Collapsing Margins:
In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.
My theory is that since your first element is next to the body the two margins combine and are applied to the body: this forces the body's content to start below the applied collapsed margin in compliance with the box model.
There are situations where the margins do not collapse which might be worth playing around with (from Collapsing Margins):
* floated elements
* absolutely positioned elements
* inline-block elements
* elements with overflow set to anything other than visible (They do not collapse margins with their children.)
* cleared elements (They do not collapse their top margins with their parent block’s bottom margin.)
* the root element
Solution 3:
This are some of the ways to avoid margin collapsing between parent-child elements. Use the one that fits better with the rest of your styling:
- Set
display
to other thanblock
. - Set
float
to other thannone
. - Remove the margin, and use instead
padding
. For example if you hadmargin-top: 10px
, replace withpadding-top: 10px;
. - Remove the margin, and use instead
position
(absolute
orrelative
) with attributestop
,bottom
, etc. For example if you hadmargin-top: 10px
, replace withposition: relative; top: 10px;
. - Add a
padding
or aborder
in the side where the margins are collapsing, to the parent element. The border can be 1px and transparent. - Set
overflow
to other thanvisible
to the parent element.