Jonah Jonah - 4 months ago 8
CSS Question

Pushing content below a position:fixed top nav so it's visible

This problem arises when you are using a

position:fixed
top nav bar: Since the nav bar is out of the document flow, the initial content that you put after it will be hidden by the nav bar itself. This fiddle shows my solution which uses an extra spacer div and
padding-top
:

http://jsfiddle.net/MFwJT/

html



<div class="fixednav">some nav stuff</div>
<div class="navspacer"></div>
main content which should not be covered by nav


css



.fixednav { position:fixed; width: 100%; height: 30px; background: #999 }
.navspacer { padding-top: 30px; } /* This works */


2 questions




  1. Is there a better solution?

  2. If you change
    padding-top
    to
    margin-top
    , the nav bar behaves as if the spacer came before it rather than after it. I'd like to know why this happens.



To clarify question 2,
margin-top
produces this:

Imgur

whereas
padding-top
produces this (the correct behavior):

Imgur

Answer

Is there a better solution

IMHO, better solution would be to avoid a fake spacer div navspacer and instead, go with the span as you can easily achieve your target with a single div, using line-height and without a fake div

Example Fiddle

CSS

.fixednav {
    width: 100%;
    height: 30px;
    background: #999;
    line-height:90px; /*this is the key here*/
}
.fixednav > span {
    position:fixed;
    display:block;
    width:100%;
    line-height:30px;/*this is the key here*/
}

HTML

<div class="fixednav"> 
    <span>some nav stuff</span>
    main content which should not be covered by nav
</div>

Question 2

If you change padding-top to margin-top, the nav bar behaves as if the spacer came before it rather than after it. I'd like to know why this happens.

when you give the padding-top: 30px;, it is applied to the inside of the content area, making the whole div height (30px + if anything is in content), check this demo to see it

when you give margin-top: 30px;, it is applied to the outside of the content, demo and the contents overlap as FIXED position divs do not follow the document flow but the viewport flow!!