March 14, 2012
Jquery Browser Resize center Div even on scroll
Question by Joe
I have this code…
<style type="text/css">
#container {
width: 200px;
height: 200px;
background-color: #567;
}
</style>
<div id="container">
My center div...
</div>
<script type="text/javascript">
$(window).resize(function(){
$('#container').css({
position:'absolute',
left: ($(window).width() - $('#container').outerWidth())/2,
top: ($(window).height() - $('#container').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
</script>
This works great except if I scroll to the bottom of the page it will not center the DIV in the middle of the browser screen based on the new coordinates of where I am at in the position of the page. So my question is, if I click to open this DIV, what can I do to center the DIV if I am scrolled to the bottom of a long page?
Answer by whiteatom
Your script will only centre on the window at the top of the page.. top is relative to the document, not the window – try position:fixed and then your centring script should work.
Answer by Starx
The best way for a horizontal center is to give margin: 0 auto
CSS. As for the vertical centering, you current way is good enough.