gpt4 book ai didi

jquery - 将 div 垂直居中会在刷新时中断

转载 作者:行者123 更新时间:2023-11-28 01:56:22 25 4
gpt4 key购买 nike

我使用以下代码将一个 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 被推到底部而不是留在中间。

谁能解释一下为什么?

最佳答案

我没有看到您拥有的所有代码,所以我不知道为什么它会在 Chrome 中执行此操作(因为我的代码没有执行此操作)。

这两个 div 可能有一个“折叠边距”。您可以将 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>

关于jquery - 将 div 垂直居中会在刷新时中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16747251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com