Understanding CSS Position Absolute for good!

Stop loosing your elements in the screen by understanding how an object figures where it is supposed to sit.

Positioning an element absolutely is more about the element’s container position than its own. To be able to position itself, it has to know which parent div am I going to position myself relative to.

The code below shows four nested divs. .box-1 to .box-3 are centered by display: flex and margin: auto only. .box-4 doesn’t have margin set and it sits in its default position in the document flow. 

<body>
  <div class="box-1">
    <div class="box-2">
      <div class="box-3">
        <div class="box-4"></div>
      </div>
    </div>
  </div>
</body>

The position property is unset to all elements.

body {
  display: flex;
}

.box-1,
.box-2,
.box-3 {
  display: flex;
  margin: auto;
}

.box-4 default position .box-4 default position

To be able to position itself, an element has to know two things:

On applying position: absolute to .box-4 the element is removed from the normal document flow and since its coordinates are not set, it simply stays at the default position, its parent div upper left corner.

.box-4 position absolute without offset. .box-4 position absolute without offset.

By setting top: 0 and left: 0 the element then has to know which parent it will consider as reference point. To be a reference, the element has to be positioned to the screen with position: relative.box-4 then starts asking its parent divs if they are positioned. At first, it asks .box-3 and gets No, I am not positioned. as an answer. The same goes with .box-2 and then .box-1 , since all of them have position: unset.

As .box-4 was unable to find a positioned parent, it positions itself relative to the body, because that element is always positioned to the screen:

.box-4 position absolute. Parent divs position unset. .box-4 position absolute. Parent divs position unset.

If we set position: relative to .box-1, when .box-4 asks it: Are you positioned? it gets Yes I am. as an answer. And then .box-4 will be positioned relative to .box-1:

.box-4 position absolute. .box-1 position relative. .box-4 position absolute. .box-1 position relative.

The same goes for .box-2 and .box-3.

The absolutely positioned element will position itself relative to the nearest positioned ancestor.

As soon as it finds a positioned ancestor, the position of the elements above that one are no longer relevant. The images below show the layout on setting position: relative to .box-2 and .box-3, respectively:

.box-4 position absolute. .box-2 position relative. .box-4 position absolute, .box-2 position relative.

.box-4 position absolute. .box-3 position relative. .box-4 position absolute, .box-3 position relative.

You can also find a video explanation at Code Sketch Channel 🎬.

Thanks for reading! ✌️