1

I'm working on a single page website with a fixed header at the top that has a navigation menu. The navigation menu links to divs on the page.

The issue is that when you click on one of the links the header covers up the section title. I'm wondering how this can be fixed without adding a ton of padding at the top of each div.

Here's the page: http://arifolmancohen.com/Ari/index.html

Ben Davidow
  • 1,175
  • 5
  • 23
  • 51

2 Answers2

3

I see you are using jQuery, so perhaps this snippet I found just the other day is exactly what you are looking for.

This issue you have is a href=#target's automatically find the element with the matching ID#target (then name=#target, ...) and bring that to the top of the page. However, in your case, because you have a fixed header, the header will cover the top of whatever is brought to the top of the page!

SO, by subtracting the height of your fixed element (95px) from where the page would normally be scrolled to, you prevent your fixed header from covering your content.

Include the following JavaScript between your </body> and </html> tags at the end of your HTML page:

(function($) {
    $('.main-nav a[href^="#"]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top - 95
                }, 1200);
                return false;
            }
        }
    });
})(jQuery);
Douglas Denhartog
  • 2,036
  • 1
  • 16
  • 23
2

I think scrolling with offset is only possible with JavaScript. With it you can scroll to the appropriate heading element when a navigation link is clicked. Check out this answer and try adding (or subtracting?) to the offset.

$('html, body').animate({
  scrollTop: $el.offset().top
}, 1000);

This is for a smooth scroll, you can use 0 ms for an instant scroll.

Community
  • 1
  • 1
silvenon
  • 2,068
  • 15
  • 29