position: absolute takes an element out of the normal flow. Other elements act as if it were not there, and you place it with top, right, bottom and left.
Placed relative to what? To its nearest ancestor that has a position other than static. If there is none, to the page itself.
<style>
.wrap { position: relative; height: 130px; background: #f4f9fc; border: 1px solid #1a5276; }
.tl, .br, .center { position: absolute; padding: 6px 10px; color: #fff; background: #1a5276; }
.tl { top: 0; left: 0; }
.br { bottom: 0; right: 0; background: #d94a00; }
.center { top: 50%; left: 50%; transform: translate(-50%, -50%); background: #27ae60; }
</style>
<div class="wrap">
<span class="tl">top left</span>
<span class="center">centered</span>
<span class="br">bottom right</span>
</div>
The parent has position: relative, which makes it the reference. All three children measure from its edges.
The centering trick
top: 50%; left: 50% puts the top-left corner of the element at the center. transform: translate(-50%, -50%) then moves it back by half its own size. You will meet transforms in translate.
What changes when something is absolute
- It no longer takes up space, so siblings move up to fill the gap.
- A width of
autoshrinks to fit its content, instead of stretching. - It can overlap other elements. z-index controls the order.
Typical uses
Badges and notification dots, close buttons in a corner, tooltips and dropdown menus, image captions on a photo.
The element flies to the corner of the page
position: relative. This is the number one position bug.