← Snippets - Script

Set Anchor Movement to Account for Height of Sticky Header

On sites that have sticky headers and anchor links, you need to set script to specifically account for the height of that header. Otherwise, when someone goes to an anchor link, the start of the area will be covered up by the sticky header.

Bootstrap 5

So far, we’ve been able to do this completely without script!

In your CSS, somewhere that makes sense (for example, in your header.scss), put CSS like this. You can also use media queries to change the scroll-padding-top if the height changes based on the size of the device.

html {
  scroll-behavior: smooth;
  scroll-padding-top: 66px; //sticky header height
}

Then, in your cms.scss file, within the .edit class, make sure to also add this so that things don’t break within the CMS:

html {
    scroll-behavior: initial;
    scroll-padding-top:initial;
  }

Example Sites


Bootstrap 3 / 4

Script - scripts.js

Put this inside the window load function that determines if the site is in the editor—ABOVE that if/else statement. Should be the first thing after the start of the window.load, basically.

var id = window.location.hash;
if( id.charAt(1) != "!") {
  if (window.location.hash.length > 0 && $(' ' + id + ' ').length == 1) {
    $('html, body').animate({
      scrollTop: $(id).offset().top - 85 // replace this with height of sticky header
    }, 500);
  }
}

Part Two

Put this in the large function.

$('a[data-link-type-id=anchor]').click(function(){
  var id = $.attr(this, 'href').split('#')[1];
  $('html, body').animate({
    scrollTop: $('#'+ id).offset().top - 85 //replace this with height of sticky header
  }, 500);
});

Example Sites

Tags: bs3, bs4, anchor, sticky, scroll