The "position" property helps to set the position of an element. "top", "left", "right" and "bottom" properties are used to define the final position of an element.
There are four types of positions in CSS, namely:
- static
- relative
- absolute
- fixed
static
"static" is the default position of an element according to DOM.
relative
"relative" is used to position an element relative to its previous position. Here, "top", "left", "right" and "bottom" properties are used to define the final position of an element.
p{
position: relative;
top: 10px;
left: 10px
}
Here, the paragraph (p) will be moved 10px to the bottom and 10px to the right from it's previous position.
absolute
"absolute" is used to remove an element from the DOM and give it an independent position, i.e. it neither affects positions of other elements nor gets affected by them. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block.
p{
position: absolute;
top: 10px;
left: 10px
}
Here, the paragraph (p) will be positioned 10px to the right and 10px below its closest ancestor or containing block.
fixed
"fixed" is removed and element from the flow of the DOM and position it relative to the browser viewport. It is generally used to position chat boxes, alerts, etc.
p{
position: fixed;
top: 10px;
left: 10px
}
Here, the paragraph (p) will be positioned 10px to the right of the browser viewport's left extreme and 10 px to the bottom of the browser viewport's upper extreme.