垂直居中高度未知的div

时间:2013-05-24 13:03:41

标签: javascript jquery css pageload

我在页面上有一个div(#box),它绝对位于窗口顶部和底部的百分比。当然,这会在窗口尺寸发生变化时调整大小,

这个div里面的内容可以是从几行到几段的任何内容。我希望这些内容始终垂直居中,永远不会超过#box的高度 - 主要内容在必要时会溢出。

HTML:

<div id="box">

    <div id="content">
        <h1>HEADING</h1>
        <div id="left">
            <p>
            // Lorem ipsum etc...
            </p>
        </div>
    </div>

</div>

CSS:

#box{
    position:absolute;
    top:15%; bottom:15%;
    background:white;
    left:50%;
}
#content{
    position:absolute;
    top:50%;
    overflow:auto;
    background:lightgrey;
}

的jQuery(JavaScript的):

function alignContent(){

    // Position box
    $box = $('#box');
    $box.css({
        'width' : $box.height() + 'px',
        'margin-left' : '-' + $box.height()/2 + 'px'
    });

    // Position content
    $content = $('#content');
    console.log( $content.outerHeight() );
    $content.css({
        // Set maxheight smaller for aesthetic purposes
        'max-height' : $box.height()-72 + 'px',
        'margin-top' : '-' + ($content.outerHeight()/2) + 'px'
    });
}
alignContent();

// Update when resized
$(window).resize(function(){
    alignContent();
});

See it working.

这种方法 - 我认为 - 非常简单并且大部分时间都可以使用。当内容对于页面加载#box来说太高时会出现问题 - 内容定位不正确(还要注意console.log返回错误的值)。调整大小再次正确对齐所有内容。

当内容比容器高时,是什么让它在页面加载时错误对齐 - 并且它是否可以轻松修复?

编辑:请原谅我英国人将其拼写为“中心”的倾向

2 个答案:

答案 0 :(得分:1)

在页面加载时不会触发resize事件,并且在DOMReady期间显式调用过早(在DOM完成时触发,但尚未加载所有辅助资源和内容)事件。您需要通过添加:

为文档onLoad明确执行相同的操作
$(window).load(function(){
    alignContent();    
});

Fiddle sample here, works fine

More info on difference between onDOMReady and onLoad found here

答案 1 :(得分:-1)

更改框的CSS,如下所示。添加overflow:scroll;。它会工作。

#box{
    position:absolute;
    top:15%; bottom:15%;
    background:white;
    left:50%;
    overflow:scroll;
}