css · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
pins a box to its 's corner.
position: absolute lifts a box out of the normal flow. The boxes around it close up as if it were gone, and its offsets now place it exactly.
Exactly where? Against its nearest ancestor: an element it sits inside, at any depth, whose position is anything except static. With no such ancestor, it uses the whole page.
So the trick is a pair: position: relative on the card, with no offsets, and position: absolute on the badge, with top and right.
<div class="card">
<span class="badge">New</span>
<h2>Lemon cake</h2>
<p>Fresh this morning.</p>
</div> .card {
position: relative;
padding: 24px;
background-color: lavender;
}
.badge {
position: absolute;
top: 8px;
right: 8px;
} Press show my page to see it here.
Remove position: relative; from .card and the badge flies to the corner of the page.
guess first
No positioned ancestor. Where does the badge go?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<p>Today's specials</p>
<div class="card">
<span class="badge">Hot</span>
<h2>Tomato soup</h2>
</div> .card {
padding: 24px;
background-color: lavender;
}
.badge {
position: absolute;
top: 0;
right: 0;
}
your turn
Your turn. Pin the heart to the photo.
Make the card the positioned ancestor, then make the heart absolute so it sits 10px from the card's top right corner.
the page you’re styling
<div class="photo-card">
<img src="dog.svg" alt="A happy dog">
<span class="heart">♥</span>
</div>your css
Press show my page to see it here.
- the card is positionednot checked yet
- the heart is absolutenot checked yet
- the heart sits 10px from the rightnot checked yet
fix it
The sale tag flies off to the top of the page. Fix it!
the page you’re styling
<h1>Garden shop</h1>
<div class="product">
<span class="sale">Sale</span>
<h2>Watering can</h2>
<p>Was £12, now £8.</p>
</div>your css
Press show my page to see it here.
- the product card is positionednot checked yet
- the tag is still absolutenot checked yet
- The tag measures from an ancestor. Which of its ancestors are positioned?
- None of them are, so the tag uses the whole page.
- Add
position: relative;to.product, then press run.
nailed it
you pinned a badge in its corner. :D
position: absolutelifts a box out of the flow.- It measures from the nearest positioned ancestor.
- Pair
relativeon the parent withabsoluteon the child.
new words in your collection
- absolute
- ancestor
- positioned
This lesson isn’t saved. A free account remembers every lesson you finish.