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.
I have a fixed navigation bar on my website that stays at the top
Share
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:
Example CSS:
For a working example, see http://jsfiddle.net/HV7QL/
Edit: CSS3 also includes the
:targetpseudo-class, which applies to an element whoseidhas been referenced by thehrefof a link in the document, or the hash value of the URL. You can apply a 40-pixel padding to the top of the:targetthat will be applied only to the section the user selects from the fixed navbar.Example CSS:
This is semantically cleaner than the method described above, but won’t work on older browsers.
Working example: http://jsfiddle.net/5Ngft/