Episode 8 of 23

Position Relative

Learn how position: relative works — offsetting elements from their normal position while keeping their space in the flow.

Position Relative

The position: relative value lets you nudge an element from where it would normally be — without removing it from the document flow.

How It Works

  1. The element is rendered in its normal position in the flow
  2. Its original space is preserved (other elements don't move)
  3. You can offset it using top, right, bottom, left
  4. The offset is relative to its own original position

Syntax

.box {
    position: relative;
    top: 20px;     /* Move 20px down from original position */
    left: 30px;    /* Move 30px right from original position */
}

Visual Example

<div class="box box-a">A</div>
<div class="box box-b">B (relative)</div>
<div class="box box-c">C</div>
.box {
    width: 120px;
    height: 120px;
    margin: 8px;
    background: #ddd;
    display: inline-block;
}

.box-b {
    position: relative;
    top: 20px;
    left: 30px;
    background: #6c5ce7;
    color: white;
}

Box B moves 20px down and 30px right — but boxes A and C stay in place. The gap where B originally was remains empty.

Understanding the Offset Properties

PropertyDirectionEffect
top: 20px↓ DownPushes element 20px down from top edge
bottom: 20px↑ UpPushes element 20px up from bottom edge
left: 30px→ RightPushes element 30px right from left edge
right: 30px← LeftPushes element 30px left from right edge

Tip: top and left are used most often. Negative values move in the opposite direction.

Use Case: Positioning Context

The most common use of position: relative isn't actually to move the element — it's to create a positioning context for absolutely positioned children:

.parent {
    position: relative;  /* Creates positioning context */
}

.child {
    position: absolute;  /* Positioned relative to .parent */
    top: 10px;
    right: 10px;
}

We'll cover this in detail in the next episode on position: absolute.

Use Case: Fine-Tuning Alignment

.icon {
    position: relative;
    top: 2px;  /* Slightly lower for visual alignment with text */
}

Key Takeaways

  • position: relative offsets an element from its normal position
  • The element's original space is preserved in the flow
  • Use top, right, bottom, left to offset
  • Most commonly used to create a positioning context for absolute children
  • Negative values move the element in the opposite direction