css - Positioning

CSS provides different ways to control how elements are positioned on a web page.

a) Static Positioning (default)

Elements are positioned according to the normal document flow.

div {

  position: static;

}

b) Relative Positioning

The element is positioned relative to its normal position.

div {

  position: relative;

  top: 20px; /* Moves 20px down from its normal position */

}

c) Absolute Positioning

The element is positioned relative to its nearest positioned ancestor (excluding static ancestors).

div {

  position: absolute;

  top: 50px;

  left: 30px;

}

d) Fixed Positioning

The element is positioned relative to the viewport, meaning it stays in the same position even when the page is scrolled.

div {

  position: fixed;

  bottom: 0;

  right: 0;

}

e) Sticky Positioning

The element toggles between relative and fixed positioning depending on the user's scroll position.

header {

  position: sticky;

  top: 0;

}