javascript - 垂直居中高度未知的div

标签 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 返回错误的值)。调整大小再次正确对齐所有内容。

当内容高于容器时,是什么导致它在页面加载时不正确对齐 - 它是否易于修复?

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

最佳答案

调整大小事件不会在页面加载时触发,并且您在 DOMReady 期间的显式调用太早(它在 DOM 完成时触发,但还没有所有辅助 Assets 和东西加载)事件。您需要通过添加以下内容明确地对文档 onLoad 执行相同的操作:

$(window).load(function(){
    alignContent();    
});

Fiddle sample here, works fine .

More info on difference between onDOMReady and onLoad found here .

关于javascript - 垂直居中高度未知的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16735642/

相关文章:

javascript - 在 Chrome 上使用 Tab 键时 iFrame 不滚动

javascript - 从数组中删除几个单词 - Javascript

javascript - dijit.Tree 从树到树的 DnD - 子节点不会在目标树中创建

javascript - 如何使这个 jQuery 移动导航脚本仅在小屏幕上触发?

CSS 循环第 n 个子模式

css - 如何破解 linear-gradient() with currentColor bug in chrome

javascript - 如何让动态内容的div自动滚动到底部?

jquery - 如何切换语义 UI 按钮中的内容?

javascript - 如何在 javascript 定时器/循环中运行 php 代码

html - 关键帧在与 LESSHat 的 LESS 混合中不起作用