html - 自动溢出和顶部属性的组合导致奇怪的滚动

标签 html css overflow css-position

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

.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 偏移元素时,它会改变元素的位置,但不会改变其父元素的高度,从而导致父元素滚动。如果您改用 margin-top,则父元素会适应元素的新高度而不是滚动。

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

关于html - 自动溢出和顶部属性的组合导致奇怪的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764839/

相关文章:

HTML/CSS - 自动调整元素大小以适应不同的屏幕尺寸

html - 如何使 3d 立方体原地旋转

javascript - AngularJS:如何在页面完全加载之前显示预加载或加载?

c++ - 运行时检查失败 #2 - 变量 'projectAverage' 周围的堆栈已损坏

css - 当 Angular 8 中出现文本溢出时动画文本滚动

html - 在 Angular 6 中将 HTML 转换为 PDF

javascript - Firebase 身份验证不起作用

c# - 从代码隐藏访问 htmlcontrols

CSS 响应能力推荐?

html - Flexbox 溢出滚动条显示在主体上而不是内部元素上