当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to vertically align a div with varying height?

问题描述:

I have a popup at MY PAGE and I need the div that pops up to be vertically centered. There will be more, since it's Tumblr and the blog has different posts so the divs will vary in height. I need it to be centered VERTICALLY in the middle so the content expands upwards and downwards. Anyway this can be done?

网友答案:

With the following simple HTML:

<div id="wrap">
    <div id="holder">
        <div id="modal">some<br>content<br>in<br>here</div>
    </div>
</div>

wrap is what you want modal vertically centered in, but holder is necessary because, with the following CSS:

#wrap {
    height:300px;
}

#holder {
    margin:0 auto;
    width:60px; height:auto;
    position:relative; top:50%;
}

#modal {
    text-align:center;
    margin:0 auto;
    width:50px;
    position:relative;
}

...the top of holder and modal will be centered within wrap, but we want the center of this dynamic content to be in the center, so with a little simple Javascript:

document.getElementById('modal').style.top = 
    "-" + document.getElementById('holder').offsetHeight/2 + "px";

...we shift modal up by half the automatic height of holder and voila! There we have it! You can see an example with background colors to give a visual indication of what's going on here: http://jsfiddle.net/jRSZV/

Try changing the contents of modal to see that it works regardless of its height.

网友答案:

Oh noes, not vertical centering with CSS. It's complicated, but read here: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html.

If you are set on JS, just position the element like so (crudely typed, 90% chance it won't work):

$('#element').css('top', parseInt(($(document).height() - $(this).height()) / 2));
$('#element').css('left', parseInt(($(document).width() - $(this).width()) / 2));

It's not really elegant, but it might work. Good luck (I would tweak that animation. It's a good design, but the animation overlap lowers it's quality).

网友答案:

for a vertically aligned div look here http://stylizedweb.com/2008/02/01/vertical-align-div/ and this might help!

but like what @blender said, this doesnt do dynamic. So I would browse through http://plugins.jquery.com/project/valign

网友答案:
var w = $(window);
$('.modal-dialog').css({
    'position': 'absolute',
    'top': Math.abs(((w.height() - $('.modal-dialog').outerHeight()) / 2) + w.scrollTop())
    //'left': Math.abs(((w.width() - $('.modal-dialog').outerWidth()) / 2) + w.scrollLeft())
});

$('html, body').animate({
    scrollTop: $('.modal-dialog').offset().top - 50
}, 500);

This piece of script will do what you are asking for. $('.modal-dialog') - This is the div you want to centralize vertically. See the commented line on the code. Uncomment it if you also want to centralize horizontally.

分享给朋友:
您可能感兴趣的文章:
随机阅读: