Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
473 views
Welcome To Ask or Share your Answers For Others

1 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...