Skip to content Skip to sidebar Skip to footer

Bootstrap Fixed Nav In Single Page Site Links Issue

I have single page site alampk.com Here I have fixed navbar at top, but when I click any link like exp,portfolio... it does move to that section but top 50px portion comes behind

Solution 1:

What you're trying to achieve here is impossible without Javascript.

You've changed the scrollTop but you need to do it after some milliseconds to get it working, e.g:

$(".nav a").click(function(){
  setTimeout(function() {
    $(window).scrollTop($(window).scrollTop() - 50);
  }, 10);
});

If you don't want to wait those milliseconds, you can also prevent the default behavior and simulate it:

$(".nav a").click(function(e){
  e.preventDefault();
  var href = e.target.href, id = "#" + href.substring(href.indexOf("#") + 1);
  $(window).scrollTop($(id).offset().top - 50);
});

Now, if you prefer a completely no-javascript solution, you'll need to workaround by putting a padding-top of 50px in each of your section tags, so the title will be visible in the way you want to.

Solution 2:

I really, in fact, think it's easy to do with just CSS. (Thanks Thomas for the tip! ;-)).

If you include a hash, #, the browser window will scroll itself into that position, trying to achieve the minimum possible position to make the element wholly visible. This, in a case of a fixed navbar, it's not desired.

The idea is to create an empty element before each linked element you want to direct to, just using CSS:

     element-you-want-to-target::before {
       display: block;
       content: " ";
       margin-top: -150px; /* the height of your navbar that will put the empty element up*/height: 150px; /* the height of the empty element that goes behind your navbar
       visibility: hidden; /* just in case */pointer-events: none;
     }

You have to be careful if before using this method, tried with putting some margins to the body or the element you wanted to target, because, in a responsive environment, won't work properly, showing the blank space.

Here is a pen to show what I did. I hope would be useful --> https://codepen.io/Mau-Di-Bert/pen/mjQwXw

Bye! 😀

Post a Comment for "Bootstrap Fixed Nav In Single Page Site Links Issue"