how is it possible to center a div's scrollbar?
This is what I have:
<div id="mydiv" style="width:1000px;overflow:auto;">
<img src="..." style="width:100%;height:250px;" />
</div>
$(window).on('resize', function () {
$('#mydiv').scrollLeft(
$( "#mydiv" ).width() - $( "#mydiv" ).width()/2
);
});
But this doesn't work. It is not exactly centering. Too bad I can't set percent 50%. The scrollLeft(() function requires an integer.
Thanks!
how is it possible to center a div's scrollbar?
This is what I have:
<div id="mydiv" style="width:1000px;overflow:auto;">
<img src="..." style="width:100%;height:250px;" />
</div>
$(window).on('resize', function () {
$('#mydiv').scrollLeft(
$( "#mydiv" ).width() - $( "#mydiv" ).width()/2
);
});
But this doesn't work. It is not exactly centering. Too bad I can't set percent 50%. The scrollLeft(() function requires an integer.
Thanks!
Share Improve this question asked Oct 25, 2013 at 14:49 JordyJordy 4,79512 gold badges51 silver badges82 bronze badges 3- Is this what you're looking for? jsfiddle/HSJft – Jason P Commented Oct 25, 2013 at 14:55
- @JasonP, yes, but when the #mydiv is resized (for example when you resize your browser), the scrollbar isn't centered any more. Check this for example: jsfiddle/HSJft/1 – Jordy Commented Oct 25, 2013 at 15:01
- I tried it, and it seems to work. jsfiddle/vJrEN @UDB is right I changed the with of your image too. – Marvin Brouwer Commented Oct 25, 2013 at 15:04
2 Answers
Reset to default 3here is your solution i have checked it with every possible width which was less than the image width. Even measured both left and right side space of scroll bar with plastic ruler ..LOL. :) to check if both sides are equal
http://jsfiddle/HSJft/5/
var outer=document.getElementById('mydiv').offsetWidth
var inner=document.getElementById('im').offsetWidth;
console.log(inner);
$('#mydiv').scrollLeft((inner-outer)/2)
<div id="mydiv" style="overflow:auto; overflow-y:hidden;width:300px">
<img id="im" src="http://eofdreams./data_images/dreams/image/image-15.jpg" />
</div>
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Easy solution:
https://jsfiddle/HSJft/21/
Vertical Scroll:
$(scrollWrapper).scrollTop(($(content).height() - $(scrollWrapper).height())/2);
Horizontal Scroll:
$(scrollWrapper).scrollLeft(($(content).width() - $(scrollWrapper).width())/2);