简体   繁体   English

jQuery将div居中于页面中间

[英]jquery center a div in the middle of the page

I am working on a Lightbox (tutorial) , a div container which opens on a click. 我正在开发Lightbox(教程) ,这是一个div容器,单击即可打开。
This div container isn´t displayed and is located under the click element. 该div容器未显示,位于click元素下方。
Now i tried to center it vertical but withouth success. 现在,我尝试将其垂直居中,但没有成功。
Found some other questions here on Stackoverflow, but no one worked for me, like this . 在Stackoverflow上找到了其他一些问题,但是没有人像这样为我工作。

$(window).resize(function() {
  $(".modal-box").css({
    top: (($(window).height()  - $(".modal-box").outerHeight() / 2) + $(window).scrollTop() + "px")
  });
});

The problem is: At the beginning the div is almost out of the bottem screen and divs below gone out of top screen. 问题是:在开始时,div几乎超出了底部屏幕,而下面的div超出了顶部屏幕。
I would have each div in the middle of the screen, no matter of the position. 无论位置如何,我都会将每个div放在屏幕中间。

As @Rakesh commented on the question, this can be done with CSS alone; 正如@Rakesh对这个问题的评论一样,这可以仅使用CSS来完成; see this fiddle https://jsfiddle.net/xc2vrghx/1/ 看到这个小提琴https://jsfiddle.net/xc2vrghx/1/

You have to use 2 div's. 您必须使用2 div。 Outer one with full 100% width/height, absolutely positioned, display set to table & alignments to center & middle - like this: 外层完全100%的宽度/高度,绝对定位,显示设置为桌子,对齐方式为居中和居中-像这样:

display: table; min-width: 100%; min-height: 100%; position:absolute;

The the inner div (which is your centered container) must have css display set to table-cell, and give center & middle alignments to this container: 内部div(这是您居中的容器)必须将css显示设置为table-cell,并为此容器指定中心和中间对齐方式:
display: table-cell; vertical-align: middle; text-align: center;

place whatever you want inside this; 将您想要的任何东西放入其中; fiddle example contains additional html inside this middle container to show as example. 小提琴示例在此中间容器中包含其他html,以作为示例。 CSS display property's table & table-cell values are playing the magic role here. CSS显示属性的表单元格值在这里起着神奇的作用。 http://colintoh.com/blog/display-table-anti-hero is a very good article to understand http://colintoh.com/blog/display-table-anti-hero是一篇非常好理解的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM