I have a div child with absolute position (blue-box) and a parent with default (static) position hanging on body (container). When I define a margin-top for the parent, div child is displaced too.
Blue-box is positioned relative to its closest positioned ancestor, so in this case is positioned relative to body, because container is positioned statically. (See https://developer.mozilla.org/en-US/docs/Web/CSS/position#absolute)
I supposed that was a problem of margin collapsing, but I read that the margins of floating and absolutely positioned elements never collapse.
(See https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing)
body {
background-color: #1f1f1f;
height: 2000px;
}
.box {
width: 100px;
height: 100px;
margin-bottom: 10px;
}
.blue-box {
background: lightskyblue;
position: absolute;
margin-top: 110px;
}
.green-box {
background: lightgreen;
}
.container {
background: rgba(0, 0, 0, 0.4);
height: 200px;
width: 200px;
margin-top: 150px;
}
<div class="container">
<div class="box blue-box"></div>
</div>
<div class="box green-box"></div>
I expected blue-box to be on top of the viewport and not inside the container box