简体   繁体   中英

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.
This div container isn´t displayed and is located under the click element.
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 .

$(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.
I would have each div in the middle of the screen, no matter of the position.

As @Rakesh commented on the question, this can be done with CSS alone; see this fiddle https://jsfiddle.net/xc2vrghx/1/

You have to use 2 div's. Outer one with full 100% width/height, absolutely positioned, display set to table & alignments to center & middle - like this:

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:
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. CSS display property's table & table-cell values are playing the magic role here. http://colintoh.com/blog/display-table-anti-hero is a very good article to understand

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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