CSS Positioning
static (default)
Normal document flow. top, left, right, bottom have no effect.
relative
Offset from its own normal position. Still occupies original space.
css
.box {
position: relative;
top: 20px; /* moves down 20px from where it would normally be */
left: 10px;
/* original space is preserved - other elements don't move */
}absolute
Removed from flow. Positioned relative to the nearest positioned ancestor (any position other than static).
css
.parent {
position: relative; /* establishes positioning context */
}
.child {
position: absolute;
top: 0;
right: 0; /* top-right corner of .parent */
}fixed
Removed from flow. Positioned relative to the viewport - stays in place while scrolling.
css
.navbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
/* stays at top of viewport always */
}sticky
Behaves like relative until a scroll threshold is reached, then acts like fixed.
css
.table-header {
position: sticky;
top: 0; /* sticks to the top of the scroll container once reached */
}Comparison
| Stays in flow | Positioned relative to | Scrolls with page | |
|---|---|---|---|
relative | Yes | Itself | Yes |
absolute | No | Nearest positioned parent | Yes |
fixed | No | Viewport | No |
sticky | Yes | Scroll container | Until threshold |
position: relativeon a parent is the most common pattern - it creates a positioning context for absolutely positioned children.
updated
did you know it?