DEV Community

Deveesh Shetty
Deveesh Shetty

Posted on

Breaking down CSS positioning

Whomever i talk to about CSS, says they struggle with positions and how they actually work

Made a few illustrations to make it little less random when you use them for the next time.

By default all the elements in the page are position: static, it means they will follow the usual sequential approach of HTML page

Elements are static by default

But sometimes you need to position elements at a different place, or in a different manner. 99% of the times you can get away by using layout properties like flex or grid, but sometimes you need to take matter into your own hands and use position property

position: relative

This is the simplest of them all, when you add this to your css, for your surprise. it does nothing, absolutely nothing by itself

Change all elements to relative position

But this position value allows you to add properties like top, right, bottom, left and also z-index. This gives you more control on where to keep the element

Adding top and left properties to relative element

position: absolute

This is little scarier than relative, and sometimes haunts me in my dreams, absolute positioning makes your element fly in the DOM. basically the element exits the sequential flow of the HTML document.

Absolute positioning an element

Absolute element will always be positioned relative to the nearest relative parent.

अर्थात् (meaning): If you position an element as absolute it will take the top, right, bottom, left (TRBL) properties based on the nearest parent which is set to position relative.

If no parent has position relative, it will fallback to the HTML root, ie the window. That's why you can see it is stuck on the top left of the page.

Adding top and left properties to absolute element

Notice it now it changes relative to the window

Now let's enclose it in a parent which has position relative, then it will be positioned with respect to the parents TRBL properties

Absolute positioning an element inside a relative parent

Adding some TRBL properties to the absolute element

Adding top and left properties to absolute element inside a relative parent

That's it, it ain't no rocket science. Mess around a little with it and you will be more confident in writing them

Also as a side note, try to avoid absolute positioning as much as you can, since it will create more problems then it might solve, ranging from pixel manipulation till responsiveness.

Originally posted on X

Deveesh Shetty
Github | X

Top comments (0)