I wanted to set a top header in a fixed position and have content scroll underneath it and came across some strangeness. If I set a margin-top to the content div that margin would also affect the header and move it down even though it's set to position:fixed. I found a workaround by setting the content div to position:relative and using top: to offset it the same amount, but I find it strange that a non-nested div can affect a fixed-positioned element and would like to know why it happens.
I get the same thing in Safari, Firefox and Chrome. In Opera the margin pushes down the content and leaves the header in place, which is what I expected it to do, but compared to the other results maybe it's Opera that has it wrong. What I'm talking about can be in seen in this JSFIDDLE (don't use Opera! :) ).
Here's the code:
css:
body {
background:#FFD;
}
#header {
position:fixed;
height:15px;
width:100%;
text-align:center;
border-bottom:1mm dashed #7F7F7F;
background-color:#EEE;
}
#content {
width:90%;
margin-top:25px;
margin-left:auto;
margin-right:auto;
background-color:#E5E5FF;
border: 1px solid #000;
}
html:
<body>
<div id="header">
HEADER
</div>
<div id="content">
<p>Text1</p>
<p>Text2</p>
<p>Text3</p>
<p>Text4</p>
</div>
</body>
Margin does not work because position of the header is fixed.
You can use margin: 0 auto with position: fixed if you set left and right . This also works with position: absolute; and vertically.
The margin-left CSS property sets the margin area on the left side of an element. A positive value places it farther from its neighbors, while a negative value places it closer.
#header {
top: 0px !important;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With