Positioning: badges, sticky bars and layers
Taking an element out of the normal flow, pinning a badge to a corner, keeping a header on screen while the page scrolls, and understanding why z-index sometimes does nothing.
By the end you can
- Place an element exactly where you want it, relative to the right parent
- Keep a header or a bar on screen while the page scrolls
- Layer things deliberately instead of guessing at numbers
- Know when positioning is the wrong tool
Easier if you did first
step 1 of 3
The five kinds of position
By default every element sits in the flow: one after another, each making room for the next. Position changes that, and there are five values.
static is the default. The element is in the flow and ignores top, left and so on.
relative keeps the element in the flow, taking up its space as usual, but lets you nudge it with top, left, right and bottom. Nothing else moves.
absolute takes the element out of the flow completely. Its space closes up behind it, and it is positioned against its nearest positioned ancestor.
That last phrase is the part to understand. An absolute element looks up through its parents for one that is positioned, meaning anything other than static. The first one it finds becomes its frame of reference. If it finds none, it uses the page itself, which is why a badge sometimes flies to the top corner of the whole document.
So the pattern is always a pair: position: relative on the box you want to pin inside, position: absolute on the thing being pinned.
fixed is positioned against the window, so it stays put while the page scrolls. sticky is the clever one, covered in the next step.
Pin the Popular badge to the top right corner of the card.
.card {
position: relative; the frame of reference
}
.badge {
position: absolute; taken out of the flow
top: 10px;
right: 10px; measured from the card's corner
}What these words mean
- static
- The default. In the flow, ignores top and left.
- relative
- In the flow, but nudgeable. Its original space is kept.
- absolute
- Out of the flow, positioned against the nearest positioned ancestor.
- fixed
- Out of the flow, positioned against the window. Stays while the page scrolls.
- positioned ancestor
- The nearest parent whose position is anything other than static.
- inset
- Shorthand for top, right, bottom and left in one line.
Easy to get wrong
position: absolute with no positioned parent
position: relative on the parent first
With nothing positioned above it, the element is measured from the page itself, so your badge ends up in the corner of the whole document instead of the corner of the card.
Using absolute positioning to build a layout
Flexbox or grid
Absolute elements are out of the flow, so nothing makes room for them. Text overlaps, boxes do not grow to fit, and every screen size needs new numbers.
What we check
- The card is the frame of reference
- The badge is positioned absolutely
- The badge really is in the card's top right corner