The position
property in CSS is used to specify the type of positioning method used for an element. It determines how an element is positioned in the document flow. The available values for the position
property are static
, relative
, absolute
, fixed
, and sticky
. Let's go through each of these with examples:
position: static
- Description: This is the default value. Elements are positioned according to the normal flow of the document.
top
,right
,bottom
, andleft
properties have no effect on a static-positioned element.
<div style="position: static; background-color: lightblue;">
This is a static positioned element.
</div>
position: relative
- Description: The element is positioned relative to its normal position. Setting
top
,right
,bottom
, orleft
will move the element away from its normal position, but it still occupies space in the normal document flow.
<div style="position: relative; left: 20px; background-color: lightgreen;">
This element is positioned 20px to the right of its normal position.
</div>
position: absolute
- Description: The element is positioned relative to its nearest positioned ancestor (an ancestor with
position
set torelative
,absolute
, orfixed
). If no such ancestor exists, it is positioned relative to the initial containing block (usually the viewport). The element is removed from the normal document flow, so it doesn't affect the position of other elements.
<div style="position: relative; background-color: lightgray;"> <div style="position: absolute; top: 10px; left: 20px; background-color: coral;"> This element is positioned 10px from the top and 20px from the left of its nearest positioned ancestor. </div> This is the nearest positioned ancestor. </div>
position: fixed
- Description: The element is positioned relative to the viewport, which means it stays in the same place even if the page is scrolled. Like
absolute
, it is removed from the normal document flow.
<div style="position: fixed; top: 0; left: 0; width: 100%; background-color: yellow;"> This is a fixed positioned element. It stays at the top of the page even when scrolling. </div> <div style="height: 1500px;"> Scroll down to see the fixed element stay at the top. </div>
position: sticky
- Description: The element is treated as
relative
until it crosses a specified point in the viewport, at which point it is treated asfixed
. Thetop
,right
,bottom
, orleft
properties determine where the element becomes sticky.
<div style="height: 150px; background-color: lightgray;"> Scroll down to see the sticky element. </div> <div style="position: sticky; top: 0; background-color: orange;"> This element will stick to the top of the viewport when you reach its scroll position. </div> <div style="height: 1500px; background-color: lightblue;"> Keep scrolling to see the sticky effect. </div>