Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 221
Brian Avatar asked Nov 25 '12 21:11

Brian


1 Answers

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:

<div class="navbar">
  <a href="#anchor1">Anchor 1</a>
  <a href="#anchor2">Anchor 2</a>
  <a href="#anchor3">Anchor 3</a>
</div>
<div class="section">
  <span id="anchor1" class="anchor"></span>
  Section Content
</div>
<div class="section">
  <span id="anchor2" class="anchor"></span>
  Section Content
</div>
<div class="section">
  <span id="anchor3" class="anchor"></span>
  Section Content
</div>​

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/

like image 190
Aaron Avatar answered Nov 05 '22 20:11

Aaron