0

I prepared this example to visualize my question:

body {
  text-align: center;
}

.child-1 {
  width: 50px;
  height: 50px;
  background: rgba(200, 200, 255, 0.5);
  z-index: 100;
  position: absolute;

}

.child-2 {
  width: 100%;
  height: 50px;
  margin-top: 100px;
  background: rgba(255, 255, 200, 0.5);
}

.case1 {
  background: red;
}

.case2 {
  background: red;
  border: 5px solid black;
}
 <div class="case1">
   <div class="child-1">
     child 1
   </div>
   <div class="child-2">
     child 2
   </div>
 </div>
<hr>
 <div class="case2">
   <div class="child-1">
     child 1
   </div>
   <div class="child-2">
     child 2
   </div>
 </div>

Case 1: Why is the default position of child1 (with position: absolute) not in the top left corner, but somehow moved down because of "margin collapsing" (as someone mentioned)? I don't understand how child2's margin (which is on the same layer as child1) could affect child1's position. And I don't understand what it has to do with collapsing margins.

Case 2: The only thing that was changed was the border of the containing element. But how can adding a border to the parent affect the position of it's childs? I don't get it.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
XENOTnet
  • 101
  • 1
  • 6
  • it's in both cases the top/left corner because maring-collapsing will move the margin outside of the parent element. You can clearly see that there is no red background in the top – Temani Afif Mar 24 '20 at 21:34
  • why is that though? Why doesn't the margin-top just push child2 down, but keep the margin inside the parent? When does this kind of margin collapsing occur? – XENOTnet Mar 24 '20 at 21:36
  • from the duplicate and if you follow the link you can read *top margin of a box and top margin of its first in-flow child* and *If the element's margins are collapsed with its parent's top margin, the top border edge of the box is defined to be the same as the parent's.* – Temani Afif Mar 24 '20 at 21:39
  • also *no line boxes, no clearance, no padding and no border separate them* --> adding border in your second example disable the margin collapsing – Temani Afif Mar 24 '20 at 21:40
  • i think absolutely nothing –  Mar 24 '20 at 21:40

0 Answers0