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>
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:
display
to other thanblock
.float
to other thannone
.padding
. For example if you hadmargin-top: 10px
, replace withpadding-top: 10px;
.position
(absolute
orrelative
) with attributestop
,bottom
, etc. For example if you hadmargin-top: 10px
, replace withposition: relative; top: 10px;
.padding
or aborder
in the side where the margins are collapsing, to the parent element. The border can be 1px and transparent.overflow
to other thanvisible
to the parent element.