gpt4 book ai didi

html - 为什么溢出:hidden affect background's visibility of a div that has a nested div with top/bottom margin?

转载 作者:行者123 更新时间:2023-11-28 06:54:46 25 4
gpt4 key购买 nike

我希望标题不是很困惑。正如您在下面的示例中看到的,有一个外部 div 和一个内部 div,我将 margin-top:100px 设置为内部 div。在“外边距区域”我们默认看不到外层div的背景。但是如果在外层div中加上overflow:hidden,背景就出现了。有人可以解释为什么会这样吗?

我希望我在这里表达了自己的意思,因为我的母语不是英语。

$("button").on("click", function() {
$(".outer").toggleClass("hidden");
});
div.outer {
background: red;
width: 100px;
}
div.outer.hidden {
overflow: hidden;
}
div.inner {
margin-top: 100px;
background: blue;
height: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>

<body>
<div class="outer">
<div class="inner"></div>
</div>
<br>
<button>toggle</button>
</body>

</html>

最佳答案

我相信这是一个名为 margin collapsing 的结果.

本质上,在没有溢出的情况下,浏览器会将内部元素的顶部边距与容器的顶部边距折叠起来。这是一个糟糕的事情。

当你添加溢出,或者绝对定位,或者 float 时,浏览器的折叠效果不会发生。

来自 the MDN :

These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.

关于html - 为什么溢出:hidden affect background's visibility of a div that has a nested div with top/bottom margin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33572852/

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