Reputation: 1645
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?
Upvotes: 0
Views: 2685
Reputation: 21890
Perhaps something like this: jsFiddle Demo Here
I added and animate function to move the #container
when the window is scrolled:
var $scrollingDiv = $("#container");
$(window).scroll(function(){
$scrollingDiv.stop().animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, 500, 'easeInOutSine' );
});
Upvotes: 1
Reputation: 79039
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.
Upvotes: 0
Reputation: 5000
im not sure exactly your question, but i do something similar like this
var top= $(document).scrollTop()+($(window).height()/2) - ($('#container').outerWidth()/2);
var left=(window.innerWidth/2) - ($('#container').outerWidth()/2);
Upvotes: 0
Reputation: 1455
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.
Upvotes: 1