Andy Andy - 2 months ago 12
CSS Question

Absolute item is not located relative to its container

I have two items in a 'relative' container.

The problem is that the 'absolute' item should be located relative to the container but it is located relative to the second 'static' item.

Example:



<div style="position:relative">
<button style="position:absolute;top: 200px">Botton</button>
<div style="margin-top: 500px">hi</div>
</div>





The div (with 'hi' text) should be located below the button but somehow the button is located 200px below the 'hi' div.

Note: If I will add border to the container it will behave as expected.

Example for the difference where there is a border and where there is not: JSfiddle

Answer

it is working as expected, because one is using position:absolute the other is using margin-top, the second one won't be doing margin-top to the sibling because the sibling is out of the flow (using position:absolute)

so instead of margin-top use position:absolute, or use margin-top on both children.

position

div {
  position: relative
}
div > * {
  position: absolute
}
button {
  top: 200px
}
span {
  top: 300px
}
<div>
  <button>Botton</button>
  <span>hi</span>
</div>

margin

button {
  margin-top: 200px
}
span {
  margin-top: 300px;
  display: block
}
<div>
  <button>Botton</button>
  <span>hi</span>
</div>

Comments