by Marina Ferreira

How to understand CSS Position Absolute once and for all

Stop losing your elements on 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 it’s going to position itself 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

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

coordinates for its x and y position set by either top , right , bottom , left

and position set by either , , , which parent it’s going to position itself relative to

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

.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 a 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 for .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 . That element is always positioned to the screen:

.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.

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 is 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 and .box-3 position relative, respectively.

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

Thanks for reading! ✌️

Originally published at marina-ferreira.github.io.