position: relative
Relative positioning offsets an element from its normal position while preserving space in the document flow. The element still occupies its original space, but is visually offset. This is useful for fine-tuning layouts without affecting other elements.
How Relative Positioning Works
CSS
/* Element with relative positioning */
.element {
position: relative;
top: 10px;
left: 20px;
}
/* Element is offset 10px down and 20px right */
/* But still occupies original space in document flow */
/* Top/right/bottom/left are offsets from normal position */
.element {
position: relative;
top: 10px; /* 10px down from top */
right: 20px; /* 20px left from right (confusing!) */
bottom: 15px; /* 15px up from bottom */
left: 5px; /* 5px right from left */
}Use Cases
CSS
/* Fine-tune element position */
.logo {
position: relative;
top: 2px;
/* Slight adjustment for visual alignment */
}
/* Position absolute child within relative parent */
.card {
position: relative;
padding: 20px;
}
.card-badge {
position: absolute;
top: -10px;
right: 10px;
/* Badge positioned relative to card */
}
/* Layering with relative and z-index */
.box {
position: relative;
z-index: 10;
/* Creates stacking context */
}Relative vs Static
Property | Relative | Static |
|---|---|---|
Flow | Preserved, space reserved | Normal flow |
top/left/etc | Offsets position | Ignored |
z-index | Works | Ignored |
Use Case | Fine-tuning, context for absolute children | Most elements |
CSS
/* Relative positioning example */
.container {
position: relative;
width: 300px;
height: 200px;
background: lightblue;
}
.item {
position: relative;
top: 20px;
left: 30px;
background: white;
padding: 10px;
/* Item is offset but space preserved below it */
}
/* Space is reserved where item would normally be */Note
Relative positioning offsets an element while preserving its space in the document flow. It's useful for fine-tuning positions and creating a positioning context for absolutely positioned children. Use it sparingly—modern layouts prefer flexbox and grid.
Next
Absolute positioning: [position: absolute](/css/position-absolute).