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; }
To be able to position itself, an element has to know two things:
- coordinates for its
x
andy
position set by eithertop
,right
,bottom
,left
- 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.
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:
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
:
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:
You can also find a video explanation at Code Sketch Channel ?.
Thanks for reading! ✌️
Written by
Marina Ferreira
Software Engineer from São Paulo, Brazil.
freeCodeCamp.org
Stories worth reading about programming and technology from our open source community.