Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position horizontal scroll bar at center of DIV

Tags:

html

jquery

css

I was trying to position horizontal scroll bar at the center of that div. I tired with window.scrollTo() but this works for page scroll and not for div scroll.

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

});

DEMO: fiddle

like image 628
Jitu Avatar asked Jul 31 '15 13:07

Jitu


3 Answers

This is an old question, but you can now use scrollIntoView for this, depending on the browsers that must be supported:

$(document).ready(function(){ document.getElementById('center').scrollIntoView({ inline: 'center' }); });

Updated fiddle

like image 73
Jono Job Avatar answered Oct 14 '22 03:10

Jono Job


The following will give you your desired effect and scroll to the center of the div through a simple change in your jQuery:

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

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

This code will set the scroll bar to the center of the inner content. But lets examine why. We know the minimum value for scrollLeft is zero, and the maximum is inner.width() - outer.width(). So, half way is easily half the maximum.

There is plenty more information on the subject here.

Demo

like image 37
Jon Avatar answered Oct 14 '22 01:10

Jon


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

});
like image 29
Guilherme Silva Avatar answered Oct 14 '22 03:10

Guilherme Silva