2

我使用以下代码将一个 div 垂直居中在另一个 div 中:

 var heightf = $('.cx1').height();
 var heightg = $('.cx2').height();
 heighth = (heightf - heightg) / 2;
 if (heighth > 0) {
    $('.cx2').css({ "marginTop": heighth });
 }

我在一个文档就绪包装器和一个窗口调整大小包装器中有这个,以便随着屏幕尺寸的变化图像保持居中(响应式)。

这似乎在所有浏览器中都可以正常工作,但是当我在 Chrome 和 Kindle Fire 上刷新时,div 被推到底部而不是留在中心。

谁能解释为什么?

4

1 回答 1

1

我没有看到你拥有的所有代码,所以我不知道为什么它会在 Chrome 中这样做(因为我的代码没有这样做)。

您可能有两个 div 的“折叠边距”。您可以将 a 添加padding: 1px 0到外部 div 以便垂直边距不会折叠。

我认为您使用窗口调整大小处理程序是因为您的外部 div 与窗口的大小相关联?所以我在下面的代码中使它与窗口的高度相同。

此代码适用于 Mac 上的 Chrome:

<!DOCTYPE html>

<style>
    body { margin: 0; }
    .wrapper { position: fixed; width: 100%; height: 100%;}
    .cx1 { background: dodgerblue; height: 100%; width: 300px; padding: 1px 0; }
    .cx2 { background: #ffc; height: 256px; width: 200px;}

</style>


<div class="wrapper">
    <div class="cx1">
        <div class="cx2">
            hello
        </div>
    </div>
</div>


<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script>

    function verticallyCenter() {
        var heightf = $('.cx1').height();
        var heightg = $('.cx2').height();
        heighth = (heightf - heightg) / 2;
        if (heighth > 0) {
            $('.cx2').css({ "marginTop": heighth });
        }
    }

    $(verticallyCenter);

    $(window).resize(verticallyCenter);

</script>
于 2013-05-25T07:49:55.987 回答