Position a badge with absolute and relative in CSS
29 Positioning, and what absolute is relative to
fairPin a badge to the top-right corner of a card. The badge should be positioned against the card, not against the page.
Stuck? Three hints, smallest first
- 1.
position: absoluteresolves against the nearest ancestor that is itself positioned. - 2. So the card needs
position: relative, even though it does not move. - 3. With no positioned ancestor, the badge escapes to the page and lands in the corner of the viewport.
<div class="card">
<span class="badge">3 left</span>
<h2 class="card__title">Kano, 08:00</h2>
<p class="card__body">Executive coach, one stop at Kaduna.</p>
</div>
.card {
position: relative; /* the anchor: without this the badge escapes */
box-sizing: border-box;
max-width: 260px;
padding: 14px;
border: 1px solid #c9cad1;
border-radius: 10px;
background: #ffffff;
}
.badge {
position: absolute;
top: -10px;
right: 10px;
padding: 3px 9px;
border-radius: 999px;
background: #a3341f;
color: #ffffff;
font-size: 0.75rem;
}
.card__title { margin: 0 0 4px; font-size: 1rem; }
.card__body { margin: 0; color: #5c5c66; font-size: 0.85rem; }
7 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
const cardRule = (/\.card\s*\{([^}]*)\}/.exec(css) || [, ''])[1];
const badgeRule = (/\.badge\s*\{([^}]*)\}/.exec(css) || [, ''])[1];
test('the badge is taken out of the flow', /position:\s*absolute/.test(badgeRule), true);
test('and offset from two edges', /top:/.test(badgeRule) && /right:/.test(badgeRule), true);
test('the card is the anchor it resolves against', /position:\s*relative/.test(cardRule), true);
test('the card itself is not offset, so it does not move', /\btop:|\bleft:/.test(cardRule), false);
test('the badge sits inside the card in the markup', /<div class="card">[\s\S]*<span class="badge">/.test(html), true);
test('nothing relies on a negative margin instead', /margin[^;]*-\d/.test(css), false);
test('the card is border-box, so the padding stays inside 260px', /box-sizing:\s*border-box/.test(cardRule), true);
Output
position: relative with no offsets looks like a no-op and is the entire mechanism: it makes the card a containing block, which is what absolute measures from. Leave it off and the badge walks up the tree looking for a positioned ancestor, finds none, and resolves against the initial containing block — so it lands near the top right of the page instead. That is the single most common absolute-positioning bug, and the fix is one declaration on the parent you forgot.