position: sticky, relative & absolute
Pin things in place
Lesson 3 of 20 · 10 min · Module 1: Layouts that adapt
Some elements should stay put: a header that remains visible while you scroll, or a "New" badge in the corner of a card. Positioning gives you that control without breaking the normal flow of the page.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Pin an element with position: sticky
- Place an element inside its container with position: absolute
- Control which element is on top with z-index
The idea
position: sticky; top: 0 keeps an element in the flow until it reaches the top of the scrolling area, then pins it there. position: absolute takes an element out of the flow and places it relative to its nearest positioned ancestor, which is why the card gets position: relative.
.card { position: relative; }
.card .ribbon {
position: absolute;
top: 8px;
left: 8px;
}
01Sticky is normal until it is not
A sticky header behaves like any other element until scrolling would move it past top: 0. From then on it stays pinned inside its scrolling container.
02Absolute needs an anchor
An absolutely positioned element looks through its ancestors for the first one whose position is not static. Without position: relative on the card, every badge would jump to the corner of the page.
.card { position: relative; } /* the anchor */
.badge {
position: absolute; /* placed inside .card */
top: 12px;
right: 12px;
}
03Stacking order
When positioned elements overlap, z-index decides which one is drawn on top. The sticky header gets z-index: 10 so content scrolling underneath never covers it.
Your turn
.site-header visible while scrolling with position: sticky, top: 0 and z-index: 10. Make every .course a positioning context with position: relative, and place each .badge in its top-right corner with position: absolute, top: 12px and right: 12px.What the checks look for
- The header sticks while scrolling
- It sticks at the very top
- It stays above the content
- Every course is a positioning context
- Badges are positioned absolutely
- Badges sit 12px from the top
- Badges sit 12px from the right
Take this with you
Sticky pins within the scroll; absolute places within the nearest positioned ancestor.
Go a little further
Tilt the first badge slightly with transform: rotate(4deg) and notice that the card layout does not move at all.