1

I need to center a DIV in the exact center of a page using jquery. My CSS style for the DIV is as follows:

#page-content #center-box{
 position:absolute;
 width:400px;
 height:500px;
 background:#C0C0C0;
 border:1px solid #000;
 }

and my jQuery for centering is as follows:

windowheight = $(window).height();
windowwidth = $(window).width();
pagecenterW = windowwidth/2;
pagecenterH = windowheight/2;
$("div#page-content div#center-box")
    .css({top: pagecenterH-250 + 'px', left: pagecenterW-200 + 'px'});

This code does not invoke any action on my page when refreshed. What am I doing wrong?

Chris Farmer
  • 24,974
  • 34
  • 121
  • 164
sadmicrowave
  • 39,964
  • 34
  • 108
  • 180
  • sorry about the code being garbled within the question text, I'm not sure how to separate the code. – sadmicrowave Apr 08 '10 at 13:08
  • select the entire code and press `Cmd+K` or `Ctrl+K`. or click the small icon with the numbers `123` at the top – Anurag Apr 11 '10 at 21:58

3 Answers3

4

Try this: Working Example

Make sure you don't have any styles on #page-content that are constraining center-box and try putting your jquery code in the document ready event.

/*CSS*/
#center-box{
 position:absolute;
 width:400px;
 height:500px;
 background:#C0C0C0;
 border:1px solid #000;
 }

/*js*/
$(document).ready(function(){
  var windowheight = $(window).height();
  var windowwidth = $(window).width();
  var pagecenterW = windowwidth/2;
  var pagecenterH = windowheight/2;
  $("div#center-box")
      .css({top: pagecenterH-250 + 'px', left: pagecenterW-200 + 'px'});
});

/*html*/
<body>
  <div id="center-box">

  </div>
</body>
Jon
  • 5,956
  • 10
  • 39
  • 40
1

Id start with removing the + 'px' or add round brackets around pagecenterH-250 and pagecenterW-200.

What you are doing there is int + int - string.

Fabian
  • 13,603
  • 6
  • 31
  • 53
0

Using absolute, the box position does not change on window resize (landscape to portrait for example). Use fixed instead. See jQuery center element to viewport using center plugin for a basic example.

Community
  • 1
  • 1
Mike
  • 1,883
  • 3
  • 23
  • 17