CSS Position

The CSS position property determines how an element is positioned in the document flow. It affects the layout and stacking context of elements.

Understanding the Position Property

The position property has several values, each defining a different positioning method:

  • static: Default positioning. Elements are positioned according to the normal flow of the document. top, right, bottom, and left properties have no effect.
  • relative: Positioned relative to its normal position. top, right, bottom, and left properties offset the element from its normal position.
  • absolute: Positioned relative to the nearest positioned ancestor (i.e., an ancestor element with a position value other than static). If no such ancestor exists, it's positioned relative to the initial containing block.
  • fixed: Positioned relative to the viewport, which means it stays in place when the page is scrolled.
  • sticky: A hybrid of relative and fixed positioning. The element is treated as relative until it crosses a specified threshold, then it is treated as fixed.

Syntax

The syntax for the CSS position property is:


/* Position Property Syntax */
selector {
    position: ;
    top: ; /* optional */
    right: ; /* optional */
    bottom: ; /* optional */
    left: ; /* optional */
}

        

Examples

Example 1: Static Positioning


/* Static Positioning */
.static-example {
    position: static;
}

            
This element is positioned statically, which means it follows the normal document flow.

Example 2: Relative Positioning


/* Relative Positioning */
.relative-example {
    position: relative;
    top: 20px;
    left: 30px;
}

            
This element is positioned relative to its normal position, offset by 20px from the top and 30px from the left.

Example 3: Absolute Positioning


/* Absolute Positioning */
.absolute-example {
    position: absolute;
    top: 50px;
    right: 20px;
}

            
This element is positioned absolutely relative to the nearest positioned ancestor.

Example 4: Fixed Positioning


/* Fixed Positioning */
.fixed-example {
    position: fixed;
    bottom: 10px;
    right: 10px;
}

            
This element is positioned fixed to the bottom right of the viewport and remains in place when scrolling.

Example 5: Sticky Positioning


/* Sticky Positioning */
.sticky-example {
    position: sticky;
    top: 0;
}

            
This element sticks to the top of the viewport once you scroll past it.