How to place horizontal scrollbar in the center of DIV

I was trying to position the horizontal scrollbar in the center of this div. I'm tired of window.scrollTo () but this works for page scrolling, not div scrolling.

$(document).ready(function(){
    var outerContentWidth = $('.abc').width();
    var scrollPosition = outerContentWidth/2;
    $('.abc').scrollLeft(scrollPosition);

});

      

DEMO: violin

+3


source to share


3 answers


Below you will get the effect you want and scroll to the center of the div via a simple change in jQuery:

$(document).ready(function(){
    var outerContent = $('.abc');
    var innerContent = $('.abc > div');

    outerContent.scrollLeft((innerContent.width() - outerContent.width()) / 2);        
});

      

This code sets the scrollbar to the center of the inner content. But let's look at why. We know the minimum value for scrollLeft is zero and the maximum is inner.width () is outer.width (). So half is easily half the maximum value.



More information on the topic here .

Demo

+4


source


$(document).ready(function(){
    var scrollPosition = ($('#viewContainer').width()/2 + $('.abc').width())/2;
    $('.abc').scrollLeft(scrollPosition);

});

      



0


source


If you want to scroll so that the middle div is visible, just set scrollPosition

like this:

var scrollPosition = $('.page').width()*2; // scroll by 2 pages, so third page is visible.

      

http://jsfiddle.net/cxkmkb0o/3/

Otherwise, if you want the middle page to be centered in the view as well, you should add an offset to what I suggested.

EDIT: Also you should notice that the pages in your fiddle do not have the same width as the "view". You have to change the width

pages to min-width

to make sure they accept the correct width. In addition, you must consider borders when positioning elements; each side border increases the width of the element. Here's the updated fiddle

0


source







All Articles