Both relative and absolute are part of CSS positioning used to control how elements are placed on a web page, but they behave very differently.
π― 1. position: relative
- The element remains in the normal document flow, meaning it still takes up space on the page.
- You can move it relative to its original position using
top,right,bottom, orleft. - Other elements do not fill its space even after moving.
π§© Example:
<div class="relative-box">Relative Box</div>
.relative-box {
position: relative;
top: 20px; /* moves 20px down from its original spot */
left: 30px; /* moves 30px to the right */
background: lightblue;
}
π Key point: The element shifts visually but its original space remains reserved.
π― 2. position: absolute
- The element is removed from the normal flow of the page.
- It’s positioned relative to its nearest positioned ancestor (an ancestor with
position: relative,absolute, orfixed). - If no positioned ancestor exists, it’s positioned relative to the
<html>(viewport).
π§© Example:
<div class="parent">
<div class="absolute-box">Absolute Box</div>
</div>
.parent {
position: relative; /* sets positioning context */
width: 300px;
height: 200px;
background: lightgray;
}
.absolute-box {
position: absolute;
top: 20px;
left: 40px;
background: coral;
}
π Key point: The .absolute-box is positioned inside .parent, 20px from the top and 40px from the left.
π§ Main Differences:
| Property | relative |
absolute |
|---|---|---|
| Document flow | Stays in flow | Removed from flow |
| Position reference | Its original position | Nearest positioned ancestor |
| Space reserved | β Yes | β No |
| Common use | Small visual tweaks | Overlays, tooltips, popups |
β In short:
- Use
relativewhen you want to nudge an element slightly from where it normally appears. - Use
absolutewhen you want to place an element precisely without affecting others.