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

前端之家收集整理的这篇文章主要介绍了html – 为什么1px边框取消100px margin-top并杀死滚动条?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这对我来说还没有意义.我错过了什么?

代码低于和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;
}@H_403_5@ 
 
<div class="middle">
  <div>Text</div>
</div>@H_403_5@ 
 

Box-sizing:border-Box;没有任何区别.添加border会导致vertical margins to not collapse,但到底是怎么回事?

>带边框:没有滚动条
>没有边框,两个顶部边距会崩溃,因此所需的垂直空间应该会减少,但我们会在全高体上获得一个垂直滚动条.

解决方法

这是由于保证金崩溃:

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,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没有边框时,应用于.middle div的边距最终会在其外部有效地使身体具有高度:100vh;和margin-top:100px;.这是导致滚动条的原因.

边距为.middle,边距包含在.middle中,因此身体只有高度:100vh;没有滚动条.

作为对此的确认,如果您要向身体添加边框,您会发现获得相同的结果.

* {
  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;
}@H_403_5@ 
 
<div class="middle">
  <div><a href="https://iDoRecall.com">Text</a>
  </div>
</div>@H_403_5@
原文链接:https://www.f2er.com/html/227246.html

猜你在找的HTML相关文章