Intermediate · CSS layout and responsive design · topic 26 of 64 · 25 min
Positioning and stacking
Explanation
Normal flow first
By default every element is position: static. It sits in the normal flow: blocks stack from top to bottom and inline content flows like text. Use flexbox and grid for layout; use positioning only for special cases like badges, overlays and sticky headers.
| Value | Moves relative to | Still takes its space? |
|---|---|---|
| static | Not moved (default) | Yes |
| relative | Its own normal place | Yes |
| absolute | The nearest positioned ancestor | No |
| fixed | The browser window (viewport) | No |
| sticky | Normal, until it reaches an edge while scrolling | Yes |
The badge pattern
.card {
position: relative; /* becomes the reference for children */
}
.card .badge {
position: absolute;
top: 8px;
right: 8px;
}An absolute element looks up the tree for the nearest ancestor whose position is not static. Giving the card position: relative (without moving it) makes the card that reference. Without it, the badge would jump to the corner of the whole page.
Sticky and fixed
.site-header {
position: sticky;
top: 0;
z-index: 10;
background: white;
}
.pay-bar {
position: fixed;
inset: auto 0 0 0; /* top right bottom left: stuck to the bottom */
}inset is a shorthand for top, right, bottom and left. inset: 0 stretches an absolute or fixed element over its whole reference box, which is useful for overlays.
z-index and stacking
When positioned elements overlap, z-index decides who is on top: higher numbers come forward. z-index only works on positioned elements (and on flex or grid items). Elements are grouped into stacking contexts, so a child can never rise above its parent's group, however big its number.
Watch the lesson
Positioning and stacking · 1/6
Normally elements follow the normal flow, one after another. position lets you break out of it.
Prefer a video by a teacher? Find free videos on “css position relative absolute fixed sticky z-index tutorial” on YouTube ↗
In real life: A sticky "Pay now" bar in a train booking app
On the passenger details page, the total fare and the "Pay now" button sit in a bar with position: fixed at the bottom of the screen, so the user can pay from anywhere while scrolling through the passenger list. The page has padding-bottom equal to the bar height, so the last passenger form is never hidden.
Practice (0/2 done)
Place the .badge in the top-right corner of the .card: give .card position: relative, and .badge position: absolute with top: 8px and right: 8px.
Make the <header> sticky: position: sticky, top: 0 and z-index: 10.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.