0
0
CssConceptBeginner · 3 min read

What is position relative in CSS: Explanation and Example

In CSS, position: relative means an element is positioned relative to its normal place in the page layout. You can move it using top, left, bottom, or right properties without affecting other elements' positions.
⚙️

How It Works

Imagine you have a picture hanging on a wall. Normally, it stays exactly where you put it. Using position: relative is like telling the picture, "Stay where you are, but you can shift a little bit up, down, left, or right." The picture's original spot still counts for the room's layout, so other things around it don't move.

In web pages, elements flow in a natural order. When you set position: relative, the element keeps its original space but can be nudged around visually. This is different from position: absolute, where the element is taken out of the normal flow and can overlap others.

💻

Example

This example shows a blue box moved 20 pixels down and 30 pixels right from its normal spot using position: relative.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Position Relative Example</title>
<style>
  .box {
    width: 100px;
    height: 100px;
    background-color: #007BFF;
    position: relative;
    top: 20px;
    left: 30px;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: Arial, sans-serif;
  }
</style>
</head>
<body>
  <div class="box">Box</div>
</body>
</html>
Output
A blue square box labeled 'Box' shifted 20 pixels down and 30 pixels right from its original position, with white text centered inside.
🎯

When to Use

Use position: relative when you want to slightly move an element without disturbing the layout around it. For example, you might want to nudge a button or image for better alignment or visual effect.

It’s also useful as a reference point for absolutely positioned child elements. When a parent has position: relative, its children with position: absolute will position themselves relative to that parent, not the whole page.

Key Points

  • Does not remove element from normal flow: Space for the element remains reserved.
  • Allows visual shifting: Use top, left, bottom, right to move it.
  • Useful for positioning child elements: Acts as a reference for absolutely positioned children.
  • Does not affect other elements' layout: Nearby elements stay in place.

Key Takeaways

position: relative moves an element visually without changing its space in the layout.
Use top, left, bottom, or right to shift the element from its normal spot.
It keeps the element in the flow, so other elements don’t move.
Set position: relative on a parent to control absolutely positioned children.
Great for small adjustments and layering effects without layout disruption.