auto overflow 和 top 属性 的组合导致奇怪的滚动

Combination of auto overflow and top property causes weird scroll

我需要一些帮助来理解为什么会发生这种情况。

.itemtop 属性设置为170px时,由于overflow: auto滚动全部乱七八糟。但是,如果我使用 margin-top 而不是 top,滚动会如我所料。

为什么会发生这种情况?在使用 top 而不是 margin-top 时,要采取什么步骤来解决滚动异常问题?

.container {
  width: 100vw;
  min-height: 100vh;
  background-color: #aa0000;
  overflow: auto;
}

.item {
  width: 200px;
  min-height: 1000px;
  position: relative;
  margin: 0 auto;
  background-color: #aaaa00;
  top: 170px;
  /*VS*/
  /*margin-top: 170px*/
}

.footer {
  height: 200px;
  background-color: #212121;
}
<div class="container">
  <div class="item">
  </div>
</div>
<div class="footer">
</div>

View on CodePen

我认为这与相对定位与 top 等偏移的工作方式有关。
对于 position:relative:

The element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static.

-- position @ MDN

因此,当您用 top 偏移元素时,它会更改元素的位置但不会更改其 parent 的高度,从而导致 parent 滚动。如果您改用 margin-top,则 parent 会适应元素的新高度而不是滚动。

删除overflow:auto有助于演示。使用 top,元素超出其 parent 的范围。使用 margin-top,parent 变高以适应。

首先要知道,滚动没有混乱,但这就是溢出的工作原理。溢出 属性 指定如果内容溢出元素的框“w3schools”会发生什么。如果你不希望滚动显示并隐藏其余内容,请使用 overflow: hidden.

现在,为什么当您使用 "margin-top" 时一切正常,而使用 "top" 时却不行。这与溢出和滚动无关。发生这种情况是因为您正在使用具有相对值的位置 属性。当您使用 top:170px 时,项目将相对于其容器定位。