What is CSS Position Property?


Position in CSS

The position property is used to define how HTML elements are aligned on the document flow, there are five different types of position property in CSS which helps to lay out our website.

syntax to use position property: position:position-type;

Types of Position

  • Static

  • Relative

  • Absolute

  • Fixed

  • Sticky

Static Position

By default, HTML elements are positioned statically. They are not affected by left, right, or top properties. The static is always positioned elements according to the normal flow of the document.

syntax :

/* it doesn't change flow of document as it's default behaviour */
position:static;

Relative Position

It is used to calculate the position of an element concerning the element's initial/static position by using the top, left, right, and bottom properties. The relatively positioned element changes its position according to the specified in CSS but all other element doesn't affect by it.

Let's see the below code pen example:

Absolute Position

The position absolute takes elements out of the normal flow of the document. If we apply position absolute on any element then it behaves like it's not present in the document and its original position is occupied by other elements.

Let's see the below example there are three boxes red, green, and blue and if we make the green box absolute then it's taken out of the flow of the document. And if we apply top:300px then, the green box move 300px below from the top of the yellow container as we specified the yellow container as relative.

Fixed Position

Fixed position property takes the elements out of the flow of the document and fixed them according to the calculation of top, right, left and bottom properties.

Let's understand it using the below codepen, we have three boxes where we have made green fox fixed at the top 10px and left 200px. If we scroll the page we can see the position of the green box doesn't change.

Sticky Position

The sticky position property is similar to fixed but it doesn't take element out of the flow of the document.

Let's understand it using the below codepen, we have three boxes where we have made green fox sticky at the top 10px and left 200px. Now you can observe top 10px doesn't work until we scroll the page, if we scroll it green box go up to 10px from the viewport and then stick to it.

Thanks for reading, Happing learning ๐Ÿ˜€

ย