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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!