CSS positioning determines how an element is placed on the page. There are several positioning types:
1️⃣ Static (default)
- Default positioning for all elements
- Follows normal document flow
top,left,right,bottomhave no effect
div {
position: static;
}
2️⃣ Relative
- Element is positioned relative to its normal position
- Can move using
top,left,right,bottom - Space for the element is still reserved in the flow
div {
position: relative;
top: 10px; /* moves element 10px down */
left: 20px; /* moves element 20px right */
}
3️⃣ Absolute
- Element is positioned relative to its nearest positioned ancestor (
relative,absolute,fixed) - Removed from normal flow → other elements behave as if it’s not there
div.parent {
position: relative;
}
div.child {
position: absolute;
top: 10px;
right: 10px;
}
- Here,
.childis 10px from top & right of.parent, not the whole page
4️⃣ Fixed
- Element is positioned relative to the viewport
- Stays in the same place even when scrolling
div {
position: fixed;
top: 0;
right: 0;
}
- Example: sticky header, back-to-top button
5️⃣ Sticky
- Acts like relative until a scroll threshold, then behaves like fixed
- Requires top, left, etc. to work
div {
position: sticky;
top: 0;
background: yellow;
}
- Example: Table headers that stick while scrolling
⚡ Summary Table (Quick)
| Position | Relative To | Flow | Use Case |
|---|---|---|---|
| static | normal document flow | yes | default |
| relative | itself (original position) | yes | small offsets |
| absolute | nearest positioned ancestor | no | dropdowns, tooltips |
| fixed | viewport | no | sticky header, floating button |
| sticky | nearest scroll container | yes/no | sticky table headers |
In short:
CSS positioning lets you control element placement: static/relative for flow-based layout, absolute/fixed for precise positioning, and sticky for scroll-aware elements.