我需要一些帮助来理解为什么会发生这种情况。
当 .item
的 top
属性设置为 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>
最佳答案
我认为这与相对定位与偏移量(如 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.
因此,当您用 top
偏移元素时,它会改变元素的位置,但不会改变其父元素的高度,从而导致父元素滚动。如果您改用 margin-top
,则父元素会适应元素的新高度而不是滚动。
删除 overflow:auto
有助于演示。使用 top
,该元素超出了其父元素的范围。使用 margin-top
,父级变高以适应。
关于html - 自动溢出和顶部属性的组合导致奇怪的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764839/