I have a site with a header set to position: fixed
. On one of my pages, I use scrollIntoView(true)
on an element. My problem is that when scrollIntoView
is called, the element gets positioned underneath the header. How would I fix this so that the element is shown just below the header?
I’m using the Bootstrap framework and the header is styled with navbar navbar-fixed-top
.
Advertisement
Answer
It’s a bit hacky but here’s a workaround.
JavaScript
x
13
13
1
var node = 'select your element';
2
var yourHeight = 'height of your fixed header';
3
4
// scroll to your element
5
node.scrollIntoView(true);
6
7
// now account for fixed header
8
var scrolledY = window.scrollY;
9
10
if(scrolledY){
11
window.scroll(0, scrolledY - yourHeight);
12
}
13
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/