CSS position defines how an element is positioned in the document. Here’s how each type works:
1️⃣ position: static (default)
- Default positioning.
- Elements appear in normal document flow.
top,left,right,bottomhave no effect.
2️⃣ position: relative
- Positioned relative to its normal position.
- Space is reserved in the document flow.
top,left, etc., shift the element without affecting other elements.
.relative-box {
position: relative;
top: 10px; /* moves 10px down from original position */
left: 20px; /* moves 20px right from original position */
}
3️⃣ position: absolute
- Positioned relative to nearest positioned ancestor (
relative,absolute, orsticky). - Removed from normal flow → does not affect other elements.
- Uses
top,left,right,bottomto define offset.
.absolute-box {
position: absolute;
top: 0;
right: 0;
}
4️⃣ position: fixed
- Positioned relative to the viewport (window).
- Stays fixed even on scroll.
- Removed from normal flow.
.fixed-box {
position: fixed;
bottom: 0;
right: 0;
}
5️⃣ position: sticky
- Acts like
relativeuntil a scroll threshold, then sticks like fixed. - Requires a threshold with
top,left, etc. - Useful for sticky headers or menus.
.sticky-box {
position: sticky;
top: 0; /* sticks to top when scrolling past it */
background: yellow;
}
🔹 Quick Comparison Table
| Position | Relative To | Affects Flow | Scroll Behavior |
|---|---|---|---|
| static | Normal flow | Yes | Scrolls with page |
| relative | Original position | Yes | Scrolls with page |
| absolute | Nearest positioned ancestor | No | Scrolls with ancestor |
| fixed | Viewport | No | Stays fixed |
| sticky | Nearest scrollable ancestor | Yes | Scrolls until threshold, then sticks |
In short:
- relative → shift from original spot
- absolute → remove from flow, position to ancestor
- fixed → stick to viewport
- sticky → behaves relative until scroll threshold, then fixed