In CSS, the position property is used to specify how an element is positioned in the document. It controls how an element is placed relative to its normal flow or to other elements.
Types of Positioning in CSS
static(default)- The default position of elements.
- Elements are positioned according to the normal document flow.
- Top, right, bottom, and left properties do not affect it.
div { position: static; }relative- The element is positioned relative to its normal position.
- The
top,right,bottom, andleftproperties move the element from its original position without affecting other elements.
div { position: relative; top: 20px; left: 30px; }absolute- The element is removed from the normal document flow.
- It is positioned relative to the nearest positioned ancestor (an ancestor with
relative,absolute, orfixed). - If no such ancestor exists, it is positioned relative to the
<html>(viewport).
div { position: absolute; top: 50px; left: 100px; }fixed- The element is positioned relative to the viewport (browser window).
- It does not move when scrolling.
div { position: fixed; bottom: 10px; right: 20px; }sticky- A mix of
relativeandfixed. The element stays in the normal flow until a specified scroll position is reached, then it sticks to that position. - Requires
top,bottom,left, orrightto work.
div { position: sticky; top: 0; }- A mix of
Additional Notes:
- The z-index property works with
relative,absolute,fixed, andstickybut notstatic. absoluteandfixedelements do not take up space in the normal flow.stickyrequires a scrolling container to work properly.
