CSS positioning - A Complete Guide

CSS positioning - A Complete Guide

CSS positioning is a must know CSS property for every web developer. It is used to displace the element around a fixed reference point. Through CSS position you can move any element to any part of the webpage.

There are five CSS position values available -

  1. static
  2. relative
  3. absolute
  4. fixed
  5. sticky

Properties like top, bottom, left and right are used to displace the element.

position: static;

position: static;

Static is the default CSS position of the HTML element provided by the DOM. Using position static you cannot displace the element from its position.

position: relative;

position: relative;

Relative is used to displace a HTML element relative to it's original position.

In the example below, the relative div is place after the static one. The original position of the relative div is below the static div.

It has been displaced 80px from the left from it's original position.

position: absolute;

position: absolute;

With position absolute the element moves out of the flow of the document and is placed on top of its parent element.

Other elements behave as if the absolutely positioned element is not present at its native position.

In the example below, the child div is at 150px from top and 50px from left of the parent div.

position: fixed;

position: fixed;

Position fixed is almost same as position absolute, only the different is that in absolute the element is positioned with reference to parent element but in fixed it is positioned with reference to the viewport.

Position fixed is used mostly to place components like chatbox at the bottom of the webpage.

In the example below, the div is at 10px from bottom and 5px from right of the viewport.

position: sticky;

position: sticky;

Position sticky is a combination of both position relative and sticky.

If the parent of the sticky positioned element is scrolling, initially the element remains in the normal flow of the document.

But when the defined offset reaches, it stick to its parent at the defined offset and is removed from the normal flow of the document.

In the example below, the div is at 30px from top and 100px from left of its parent. Initially the div navbar remains in the normal flow of the document but when it is at 30px from the top, its removed from the flow of the document and remains sticky to that position.

To conclude, CSS position is a very important CSS property and hope this article briefly describe and help you understand it.