Positioning

CSS positioning allows you to control the layout of elements on the page.

  • static: Default position; elements are positioned according to the normal flow.
  • relative: Positioned relative to its normal position.
  • absolute: Positioned relative to the nearest positioned ancestor.
  • fixed: Positioned relative to the viewport; stays in place when scrolling.
  • sticky: Toggles between relative and fixed, based on scroll position.

static

<div class="parent">
  <div class="box1">Box 1</div>
  <div class="box2">Box 2</div>
  <div class="box3">Box 3</div>
</div>
    Parent Box 
+-----------------+
|+---------------+|
||  Box 1        ||
|+---------------+|
|┌---------------┐|
||  Box 2        ||
|+---------------+|
|┌---------------┐|
||  Box 3        ||
|+---------------+|
+-----------------+

absolute

<div class="parent">
  <div class="box1">Box 1</div>
  <div class="box2">Box 2</div>
  <div class="box3">Box 3</div>
</div>
.parent {
  position: relative;
  height: 100px;
}

.box1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.box2 {
  position: absolute;
  bottom: 0;
  right: 0;
}
    Parent Box 
+-----------------+
|+---------------+|
||  Box 3        ||
|+---------------+|
|                 |
|  +----------+   |
|  |  Box 1   |   |
|  +----------+   |
|                 |
|     +----------+|
|     |  Box 2   ||
|     +----------+|
+-----------------+

Parent Box is the containing element. It establishes the context for absolutely positioned elements.

Box 1 and Box 2 are positioned absolutely within the parent box.

The top left corner of Box 1 is first posioned at the center of its Parent Box, then translate shifts it back by half of its own width and height, effectively centering it around that point.

Box 3 is the only static element, since absolute elements are taken out of the normal document flow, it goes to the top.