Absolute Inside Relative

Let's go back to the cat page, with everything you've done on it so far, and use absolute position the way it's used most often.

Placing an element relative to the whole page is rarely what we want. Much more often, we want to put it in a corner of another element: a badge on a card, a close button in the corner of a window, or a label on a photo.

The trick is to give the parent position: relative. Without offsets, the parent doesn't move at all, but it becomes the nearest ancestor with a position. The offsets of its children with position: absolute are then measured from its edges:

.card {
	position: relative;
}

.close {
	position: absolute;
	top: 10px;
	right: 10px;
}

Wherever the card is on the page, the element with the class close sits 10 pixels from the card's top edge and 10 pixels from its right edge. (The offsets are measured from the inner edge of the card's border.)

We've added a badge to the card of the Persian cat: a span with the class badge. Let's put it in the top right corner of the card.

Instructions

In the rule for .badge, add position: absolute, top: -10px and right: -10px. Negative offsets move an element the other way, outward, so the badge will stick out over the corner. But look where it is now: none of its ancestors has a position, so it has jumped to the top right corner of the page, and part of it is outside the page.

In the rule for #breeds li, add position: relative. The badge moves to the corner of its card, because the card is now its nearest ancestor with a position. The cards themselves don't move.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/10