Sobes.tech
Junior

What is the difference between the various methods of positioning elements in CSS?

sobes.tech AI

Answer from AI

  • static - Default position. The element is positioned according to the normal flow of the document. The top, right, bottom, left properties have no effect.
  • relative - The element is positioned relative to its normal position in the flow. The top, right, bottom, left properties offset the element from its original position, but the space it occupies in the flow remains the same.
  • absolute - The element is completely removed from the normal document flow. Its position is determined by the top, right, bottom, left properties relative to the nearest positioned ancestor (position: relative, absolute, fixed, or sticky). If no such ancestor exists, the position is relative to the initial <html> block.
  • fixed - The element is completely removed from the normal document flow. Its position is determined by the top, right, bottom, left properties relative to the viewport. The element stays in place when scrolling.
  • sticky - The element is positioned as relative until it reaches a specified position during scrolling (defined by top, right, bottom, left), after which its position becomes fixed.

Differences table:

Property static relative absolute fixed sticky
Document flow Normal Preserves Removed Removed Initially normal, then removed
Offset (top etc.) No Relative to itself Relative to ancestor/viewport Relative to viewport Relative to itself, then viewport
During scroll Scrolls Scrolls Remains in place (if ancestor is fixed) or scrolls with ancestor Remains in place Scrolls first, then stays in place

Example:

.static-box {
  position: static; /* Default position */
  width: 100px;
  height: 100px;
  background-color: lightblue;
}

.relative-box {
  position: relative;
  top: 20px; /* Shift down from normal position */
  left: 20px; /* Shift right from normal position */
  width: 100px;
  height: 100px;
  background-color: lightgreen;
}

.absolute-container {
  position: relative; /* Positioned ancestor */
  width: 300px;
  height: 300px;
  border: 1px solid black;
}

.absolute-box {
  position: absolute;
  top: 50px; /* Relative to container */
  left: 50px; /* Relative to container */
  width: 50px;
  height: 50px;
  background-color: lightcoral;
}

.fixed-box {
  position: fixed;
  bottom: 10px; /* Relative to viewport */
  right: 10px; /* Relative to viewport */
  width: 70px;
  height: 70px;
  background-color: lightsalmon;
}

.sticky-header {
  position: sticky;
  top: 0; /* Sticks to top of viewport */
  height: 50px;
  background-color: lightgoldenrodyellow;
  z-index: 10; /* Overlaps other elements when sticky */
}