How to position horizontal scroll bar at center of DIV

前端 未结 6 812
温柔的废话
温柔的废话 2020-12-18 01:51

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.



        
6条回答
  •  感情败类
    2020-12-18 02:27

    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

提交回复
热议问题