DEV Community

Rupal
Rupal

Posted on

Introduction to CSS Position

I always get confused about how to use and where to use which position value and the difference between the absolute and relative position.
Do you also have the same confusion?
So after reading the positions, I thought to write a blog post

So starts with the definition:
The Position property allows you to position an element. It sets how an element is positioned in a document.

After setting the position property(position: relative/absolute/fixed), we have to position that element using Left/Right/Top/Bottom (Ex => left:100px).
This property doesn't work until the position property sets first.

Now the diff types of position property-

1) Static positioning:
HTML elements are positioned static by default.

The static position element always positions according to the normal flow of the page.
So, if we set Left/Right/Top/Bottom it will not affect the content which has a static position property.
Ex position:static;
top: 10px;

2) Relative positioning:
It is just like a static value, but now Left/Right/Top/Bottom will work.
In this, the Left/Right/Top/Bottom will shift the element with respect to the value we assign.
The content of the relatively positioned element can be moved & overlap other elements, but the reserved space for the element is still preserved in normal flow.
Ex position:relative;
top: 100px;

3) Absolute positioning:
It is positioned relative to the first parent element that has a position other than static.
If no such element found it will position according to .

The absolute position element is removed from the normal flow also it can overlap other elements as well.
Ex position:absolute;
left: 100px;

4) Fixed positioning:
An element with the fixed position is positioned relative to the browser window, and will not move if the window is scrolled.
It can overlap other elements.
Ex position:fixed;
top: 10px;
right: 5px;
In the above example the element will fixed with the browser window to 10px from top and 5px from right.

Please share your questions or thoughts below. Thanks for reading!! Hope this blog helps you!! Cheers! 😊

Top comments (0)