为什么我的集装箱不在中心

why my container is not coming in center

本文关键字:在中心 集装箱 我的 为什么      更新时间:2023-09-26

我想在屏幕中央(水平和垂直)打开一个div。

var documnetWidth = $(document).width(),
  documentHeight = $(document).height(),
  widgetFormHeight = widgetForm.height(),
  widgetFormWidth = widgetForm.width();
widgetForm.css({
  top: documentHeight / 2 - widgetFormHeight / 2,
  left: documnetWidth / 2 - widgetFormWidth / 2
});

我的小部件在水平方向居中,但在垂直方向需要一些偏移。

您可以执行此

定义DIV的大小和位置固定,如下所示:

div {
     position: fixed;
     top: 50%; 
     left: 50%; 
     width: 200px; 
     height: 100px; 
     margin: -100px 0 0 -50px;
     z-index: 99;
}

或者,如果你不想把它放在绝对的位置,你可以给它一个宽度,并将其设置为:

div { margin: 0 auto; }

试试这个:

documentHeight = $(window).height(),

而不是:

documentHeight = $(document).height(),

按照你的方式,你得到的是文档的高度,它可能大于或小于浏览器的高度。

然后考虑到文档当前滚动的距离:

top: documentHeight/2-widgetFormHeight/2 + $(document).scrollTop(),

演示:http://jsfiddle.net/vULHL/

没有宽度或高度的绝对居中div:

http://jsfiddle.net/dFkXq/1/

它的作用就像一个固定的元素。