How do I center a DIV in the exact center of a page using jQuery?

无人久伴 提交于 2019-12-06 16:32:31

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>

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.

Mike

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!