So, I have this single page that consists of a few sections. Users can go to these sections by scrolling themselves or clicking in the navbar (a href with anchor). Due to the Bootstrap 4 navbar being fixed to the top, the content gets placed under it. Is there a way I could offset anchors by -54px, so that whenever I click on an anchor link, it would show the content below the navbar (X:54px) and not under the navbar (X:0px).
Made this codepen to show the problem I'm facing:
https://codepen.io/anon/pen/XEjaKv
Whenever you click an anchor link, it will take you to the section, however, the navbar is covering the text..
All sections are 100 viewheight.
SCSS used:
.container{ section{ height: 100vh; &#section1{ margin-top: 54px; // we need to offset the first section by 54px because of the navbar.. } &#section1, &#section3{ background-color: #ddd; } &#section2, &#section4{ background-color:#ccc; } } } html{ scroll-behavior:smooth; }
Use the .sticky-top class to make the navbar fixed/stay at the top of the page when you scroll past it.
You could add the scroll-padding-top CSS property to an HTML element with a value of 4rem . Now when you click the anchor link, the browser jumps to the anchor section but leaves padding of 4rem at the top, rather than scrolling the anchor point all the way to the top.
The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style. css file and in your HTML navigation use #NameOfTheSection . This CSS method works great for me and is super elegant!
There are a few different ways to solve it, but I think the best way is to put a hidden pseudo element ::before
each section. This is a CSS only solution, no JS or jQuery...
section:before { height: 54px; content: ""; display:block; }
https://www.codeply.com/go/J7ryJWF5fr
That will put the space needed to account for the fixed-top Navbar. You'll also want to remove the margin-top
offset for #section1
since this method will work consistently for all sections and allow the scrollspy to work.
Related
How do I add a data-offset to a Bootstrap 4 fixed-top responsive navbar?
Href Jump with Bootstrap Sticky Navbar
you can use jQuery
to override the default behavior so you don't have to change the layout ( margin, padding .. etc.)
var divId; $('.nav-link').click(function(){ divId = $(this).attr('href'); $('html, body').animate({ scrollTop: $(divId).offset().top - 54 }, 100); });
https://codepen.io/anon/pen/NYRvaL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With