While creating a web page through HTML, we either use a block-level element or an inline-element and by default they are displayed on a web page according to this feature only. We can change the positions of these elements for the purpose of designing or beautifying our web page. To do so we have to use a property of CSS, called as position.
What exactly is Position in CSS ?
The position
property of CSS is used to specify the location/position of the element on the web page. This property helps us to manipulate the location of the element. The top
, right
, bottom
, and left
properties determine the final location of positioned elements.
Types of CSS position
static
Each and every element which we use in HTML has static position by default. If we useposition: static;
on any element then the location of that element will be according to the normal flow of the page. The position of the element having static value will not be affected bytop
,bottom
,left
orright
property.
/* Syntax */
position: static;
relative
Just like static, in this also element will be positioned according to the normal flow of the page. But, for relativetop
,right
,bottom
andleft
properties will work. When we give some value to any or all of these properties then the position of the element havingrelative
value will change from it's original position as per the values oftop
,right
,bottom
, andleft
.
/* Syntax */
position: relative;
absolute
The element havingabsolute
value is removed from the flow of the document. When we give the value absolute to an element then it will be positioned relative to it's parent. The final position of the element having value as absolute will be determined by the values oftop
,right
,bottom
, andleft
.
/* Syntax */
position: absolute;
fixed
Thisfixed
value is similar toabsolute
position type. Only difference is that when we givefixed
position value to any element then the element will be positioned relative to the document not the parent. Position of fixed will not change even after scrolling.
/* Syntax */
position: fixed;
sticky
The element having asticky
value will behave likerelative
value until the scroll location of the viewport reaches a specified threshold i.e., specified value oftop
,right
,bottom
, andleft
and at that point the element will behave asfixed
.
/* Syntax */
position: fixed;
Have a look at the below codepen example which consists of all the types of CSS position.
Thanks for reading. Happy Learning ๐
ย