简体   繁体   中英

Centering parent div scroll bar, having dynamic width

I have one parent div and one child canvas, I want to center the scroll bar of parent div because I can't add any style to canvas in my project.

 #parent{ width:80vw; height:200px; border:1px blue solid; overflow-x:scroll; } #parent #child{ width:70vw; border:1px solid black; margin-left:50px; margin-right:50px; }
 <div id="parent"> <canvas id="child"> </canvas> </div>
In this snippet, margins on canvas is for demo becuase the canvas has different width and height and it is centered.
I just want to scroll the parent div where the inner canvas become in center. I have done this but no proper result

 $(document).ready(function(){ var parent = $("#parent"); var child = $("#child"); var final = (child.width() - parent.width()) / 2; parent.scrollLeft(final); console.log(final) });
 #parent{ width:90vw; height:200px; border:1px blue solid; overflow-x:scroll; } #parent #child{ width:80vw; border:1px solid black; margin-left:50px; margin-right:50px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="parent"> <canvas id="child"> </canvas> </div>
Reference to above code: How to position horizontal scroll bar at center of DIV
If you want to check in live domain what am I doing: https://mypagemaker.s3.amazonaws.com/index.html

You need to wrap your parental div in a taller parental div.

 $(document).ready(function(){ var parent = $('#parent'); var parent_sub = $('#parent > #parent_sub'); var final = (parent_sub.width() - parent.width())/2; parent.scrollLeft(final); console.log(final); });
 #parent { width:90vw; overflow-x:scroll; height:200px; border:1px blue solid; } #parent_sub { display: table; } #parent #child{ width:80vw; border:1px solid black; margin-left:50px; margin-right:50px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="parent"> <div id="parent_sub"> <canvas id="child"> </canvas> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM