0

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

A. Meshu
  • 4,053
  • 2
  • 20
  • 34
Daniel
  • 49
  • 1
  • 1
  • 10
  • *the margins of floating and absolutely positioned elements never collapse.* --> this is true but here it's the margin of the container collapsing with the one of the body. First duplicate to explain your main issue and second one to explain margin collapsing – Temani Afif Sep 22 '19 at 10:09

1 Answers1

1

As the second sentence in the Mozilla docs say, "The top, right, bottom, and left properties determine the final location of positioned elements.", you have to specify one of these values, to actually position it.

 .blue-box{position: absolute;top:10px}

Check this codepen : https://codepen.io/jsuryahyd/pen/ExYGbxr

By the way, this got me thinking too. Thank you.

Jay Surya
  • 540
  • 1
  • 8
  • 18