1

I have 2 elements, each given a margin-top of 20px. The first one is positioned absolutely. Naturally, the second element ends up at the top and recedes from the edge of the screen by 20px.

div {
  width: 200px;
  height: 200px;
}

.posa {
  margin-top: 20px;
  position: absolute;
  background-color: #1239;
}

.normal {
  margin-top: 20px;
  margin-left: 20px;
  background-color: #aaa9;
}
<div class="posa">position</div>
<div class="normal">normal</div>

CSS absolute positioned elements and margins - This question was almost answered here, but it was talking about the parent element

Questions:

  1. Why does an absolutely positioned element take the margin of the second element that was below?
  2. Why don't their margins collapse so that the .normal element will recede from the top edge by 20px and the positioned element will recede by 40px.
  3. Why does only the margin-top affect and the margin-left doesn't work that way?
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Kolenbass
  • 13
  • 3

1 Answers1

1

The margin-top of the normal element is collapsing with the body margin since it's the first in-flow child then the absolute element is using the body element as reference to move down. It's using its static position since you didn't specify any top/left/right/bottom value

Add outline to the body element to notice this:

div {
  width: 200px;
  height: 200px;
}

.posa {
  margin-top: 20px;
  position: absolute;
  background-color: #1239;
}

.normal {
  margin-top: 20px;
  margin-left: 20px;
  background-color: #aaa9;
}

body {
 outline: 1px solid red;
}
html {
 outline: 1px solid blue;
 outline-offset: -1px;
}
<div class="posa">position</div>
<div class="normal">normal</div>

There is not margin collapsing on the left so the margin of the normal element will not affect the position of the absolute element.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415