Using scrollIntoView with a fixed position header

It’s a bit hacky but here’s a workaround.

var node="select your element";
var yourHeight="height of your fixed header";

// scroll to your element
node.scrollIntoView(true);

// now account for fixed header
var scrolledY = window.scrollY;

if(scrolledY){
  window.scroll(0, scrolledY - yourHeight);
}

Edit:

A modern workaround is to use the CSS scroll-margin-top property in combination with the :target selector. Described in detail: https://www.bram.us/2020/03/01/prevent-content-from-being-hidden-underneath-a-fixed-header-by-using-scroll-margin-top/

Leave a Comment