0

I've read that:

MDN

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.

So, what can cause this behaviour?

* {
  margin: 0;
  padding: 0;
}

.block {
  width: 500px;
  height: 500px;
  background: rgba(4, 127, 214, .3);
  position: absolute;
}

.block_2 {
  margin-top: 500px;
  width: 500px;
  height: 500px;
  background: red;
}
<div class="block"></div>
<div class="block_2"></div>

That margin-top should move my red element down in theory... Why doesn't this happen?

Eva
  • 284
  • 3
  • 13
  • you never applied any margin to the absolute element so why you get surprised? – Temani Afif Nov 26 '20 at 22:42
  • 1
    Interesting behaviour! The top-margin of the statically positioned element is added as a top-margin to `body` (which is regular behaviour), and if there is no ancestor element for an absoutely positioned element, it refersto `body` as a position anchor. Therefore in your example `.block_2` is top-aligned with `body`, but `body` gets a 500px top-margin from its first child `.block` – Johannes Nov 26 '20 at 22:49
  • 1
    @Johannes *if there is no ancestor element for an absoutely positioned element, it refersto body as a position anchor.* --> it's not really this, there is an ancestor but there is no top or bottom value so the static position will be used as reference (adding top:0 will logically make it on the top of the screen) – Temani Afif Nov 26 '20 at 23:10
  • @Temani Afif So, the way I look at it, you mean that without assigning coordinates (`top`, `bottom`, `left`, `right`) to the absolute positioned element, margin collapsing will work. But it's not true actually. Here's an [example.](https://jsfiddle.net/3702b5s4/) There's an absolute positioned element without assigning `top`, `bottom`..., but as I see margin collapsing doesn't work. I can't understand... – Eva Nov 27 '20 at 15:29
  • *you mean that without assigning coordinates (top, bottom, left, right) to the absolute positioned element, margin collapsing will work.* --> I never meant that and there is no relation between position:absolute and margin collapsing. Read the duplicates to understand what is happening – Temani Afif Nov 27 '20 at 15:32

0 Answers0