CSS position controls how an element is placed on the page and how it behaves when you scroll.
✅ 1. position: static (Default)
- Default for all elements
- Follows normal document flow
top,left,right,bottomdo not work
div {
position: static;
}
📌 Use when:
No special positioning is needed.
✅ 2. position: relative
- Element stays in normal flow
- Can be moved relative to its original position
- Creates a positioning reference for children
div {
position: relative;
top: 10px;
left: 20px;
}
📌 Use when:
- Slightly adjusting element position
- As a parent for
absolutechildren
✅ 3. position: absolute
- Removed from normal document flow
- Positioned relative to the nearest positioned ancestor
- If none exists → positioned relative to the viewport
.child {
position: absolute;
top: 0;
right: 0;
}
📌 Use when:
- Dropdowns
- Tooltips
- Modals inside a container
✅ 4. position: fixed
- Removed from document flow
- Positioned relative to the viewport
- Does not move when scrolling
.navbar {
position: fixed;
top: 0;
}
📌 Use when:
- Sticky headers
- Floating action buttons
- Chat widgets
✅ 5. position: sticky
- Hybrid of
relative+fixed - Acts like relative until a scroll threshold is reached
- Then sticks like fixed
.header {
position: sticky;
top: 0;
}
📌 Use when:
- Section headers
- Table headers
- Scroll-aware UI elements
🔥 Quick Comparison Table
| Position | In Flow | Scrolls | Reference |
|---|---|---|---|
| static | ✔ Yes | ✔ Yes | Normal flow |
| relative | ✔ Yes | ✔ Yes | Itself |
| absolute | ❌ No | ❌ No | Nearest positioned parent |
| fixed | ❌ No | ❌ No | Viewport |
| sticky | ✔/❌ Hybrid | ❌ After stick | Scroll container |
🎯 Short Interview Answer
staticis the default and follows normal flow.relativeallows offsetting an element and acts as a reference for absolute children.absoluteremoves the element from flow and positions it relative to the nearest positioned ancestor.fixedsticks to the viewport during scroll.stickybehaves like relative until a scroll point, then acts like fixed.