Javascript scrollIntoView() middle alignment?

It is possible to use getBoundingClientRect() to get all the information you need to achieve this. For example, you could do something like this:

const element = document.getElementById('middle');
const elementRect = element.getBoundingClientRect();
const absoluteElementTop = elementRect.top + window.pageYOffset;
const middle = absoluteElementTop - (window.innerHeight / 2);
window.scrollTo(0, middle);

Demo: http://jsfiddle.net/cxe73c22/

This solution is more efficient than walking up parent chain, as in the accepted answer, and doesn't involve polluting the global scope by extending prototype (generally considered bad practice in javascript).

The getBoundingClientRect() method is supported in all modern browsers.


document.getElementById("id").scrollIntoView({block: "center"});

Use window.scrollTo() for this. Get the top of the element you want to move to, and subtract one half the window height.

Demo: http://jsfiddle.net/ThinkingStiff/MJ69d/

Element.prototype.documentOffsetTop = function () {
    return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
};

var top = document.getElementById( 'middle' ).documentOffsetTop() - ( window.innerHeight / 2 );
window.scrollTo( 0, top );

try this :

 document.getElementById('myID').scrollIntoView({
            behavior: 'auto',
            block: 'center',
            inline: 'center'
        });

refer here for more information and options : https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView