gpt4 book ai didi

html - 为什么 1px 的边框会抵消 100px 的 margin-top 并杀死滚动条?

转载 作者:太空狗 更新时间:2023-10-29 13:46:18 25 4
gpt4 key购买 nike

这对我来说还没有意义。我错过了什么?

Uncomment the border to kill the scrollbar

代码如下,on Codepen .

* {
box-sizing: border-box;
margin: 0; padding: 0;
}

body {
height: 100vh;
background: pink;
}

.middle {
position: relative;
top: 200px;
/* uncomment the border to kill the scrollbar! */
/* border: 1px solid green; */
}

.middle div {
margin-top: 100px;
border: 1px dashed yellow;
}
<div class="middle">
<div>Text</div>
</div>

box-sizing: border-box; 没有任何区别。添加 border导致 vertical margins to not collapse ,但到底发生了什么?

  • 带边框:无滚动条
  • 没有边框,两个上边距折叠起来,所以应该更少需要垂直空间,但我们在全高 body 上得到一个垂直滚动条

最佳答案

这是由于边缘崩溃:

If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

( https://developer.mozilla.org/en-US/docs/Web/CSS/margin_collapsing )

.middle 没有 border 时,应用于 .middle divmargin 结束于它有效地使 body 具有 height: 100vh;margin-top: 100px;。这就是导致滚动条的原因。

.middle 上的 border margin 包含在 .middle 中,所以 body 只有 height: 100vh; 并且没有滚动条。

作为对这一点的确认,您会发现如果将 border 添加到 body 中,您会得到相同的结果。

* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
height: 100vh;
background: pink;
border: 1px solid red;
}
.middle {
position: relative;
top: 200px;
/* uncomment the border to kill the scrollbar! */
/* border: 1px solid green; */
}
.middle div {
margin-top: 100px;
border: 1px dashed yellow;
}
<div class="middle">
<div><a href="https://iDoRecall.com">Text</a>
</div>
</div>

关于html - 为什么 1px 的边框会抵消 100px 的 margin-top 并杀死滚动条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31262095/

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