Reputation: 828
I'd like some help understanding why this happens.
When .item
's top
property is set to 170px, the scrolling is all messed up because of overflow: auto
. However, if I use margin-top
instead of top
, the scrolling works as I'd expect it.
Why does this happen and what are the steps to take to remedy the scrolling weirdness when using top
instead of 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>
Upvotes: 1
Views: 1562
Reputation: 153
The first thing to know, there is no mess with the scrolling but this is how overflow works. The overflow property specifies what happens if content overflows an element's box "w3schools". If you do not want the scroll to show up and hide the rest of the content, then use overflow: hidden.
Now, why when you use "margin-top" everything is working fine while not with the "top". This has nothing to do with overflow and scrolling. This happens because you are using position property with relative value. When you use top:170px, the item will be positioned relative to its container.
Upvotes: 0
Reputation: 29178
I think this has to do with the way relative positioning works with offsets like top
.
For 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.
So, when you offset the element with top
, it changes the position of the element but does not change the height of its parent, causing the parent to scroll. If you use margin-top
instead, the parent accommodates the new height of the element instead of scrolling.
Removing overflow:auto
helps to demonstrate. Using top
, the element extends beyond the bounds of its parent. Using margin-top
, the parent gets taller to accommodate.
Upvotes: 1