One reason for this phenomenon is that the absolutely positioned div .overflowed
remains relative to the .outer-wrapper
, rather than the wrapper
. Thus, what appears to be overflow is actually behaving as expected.
When an element has a position:absolute
property and its ancestor or ancestors have position:relative
, it will maintain its absolute positioning in relation to the closest ancestor with position:relative
.
For instance, consider the following code snippet where I introduce another wrapper. Even if I assign position:relative to this new wrapper, it will not affect the positioning of the absolute div since there is a closer ancestor with position:relative.
If you remove the position:relative from outer-wrapper
and retain it on the new wrapper .more-wrapper
, the absolute div will then be positioned relative to the more-wrapper
.
I hope this explanation clarifies things.
.outer-wrapper {
position: relative;
padding: 100px;
background: white;
}
.more-wrapper {
position:relative;
background:red;
padding:100px;
}
.wrapper {
overflow: hidden;
height: 200px;
background: darkblue;
}
.overflowed {
position: absolute;
width: 50%;
background: lightblue;
padding: 50px;
top: 50px;
left: 50px;
font-family: sans-serif;
}
<div class="more-wrapper">
<div class="outer-wrapper">
<div class="wrapper">
<div class="overflowed">(Overflowing the wrapper)</div>
</div>
</div>
</div>
I stumbled upon your answer through a simple Google search. For more information, you can visit this link: css positioning
An element with position: absolute; is positioned relative to the nearest positioned ancestor (rather than relative to the viewport like fixed).
However, if an absolutely positioned element does not have any positioned ancestors, it will use the document body and move with page scrolling.
Note: A "positioned" element refers to one whose position is anything other than static.