Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How do I offset where my fixed nav bar takes me?

How do I offset where my fixed nav bar takes me?

Problem

I have a Fixed Navigation Bar on my website that stays at the top with links that take me to different sections further down the page. However, because my Fixed Nav Bar has a height of 40px, the beginning 40px of every section is covered up. How would I offset where my links take me by 40px using either HTML or CSS? Thanks.

Problem courtesy of: Brian

Solution

You might try absolutely positioning "dummy" anchors 40 pixels above the top of each section. You can give them zero width/height and hidden visibility to ensure that these anchors don't affect how your page is displayed. When the user clicks one of the links in your fixed navigation bar, the window will scroll to the top of the dummy anchor, 40 pixels above the beginning of its actual section.

Example HTML:


Section Content
Section Content
Section Content

Example CSS:

body {
    padding-top: 40px;
}
.navbar {
    position: fixed;
    width: 100%;
    height: 40px;
    top: 0;
    left: 0;
    z-index: 10;
    border-bottom: 1px solid #ccc;
    background: #eee;
}
.section {
    position: relative;
}
.anchor {
    display: block;
    position: absolute;
    width: 0;
    height: 0;
    z-index: -1;
    top: -40px;
    left: 0;
    visibility: hidden;
}

For a working example, see http://jsfiddle.net/HV7QL/

Edit: CSS3 also includes the :target pseudo-class, which applies to an element whose id has been referenced by the href of a link in the document, or the hash value of the URL. You can apply a 40-pixel padding to the top of the :target that will be applied only to the section the user selects from the fixed navbar.

Example CSS:

.section:target {
    padding-top: 40px;
}

This is semantically cleaner than the method described above, but won't work on older browsers.

Working example: http://jsfiddle.net/5Ngft/

Solution courtesy of: Aaron

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

How do I offset where my fixed nav bar takes me?

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×