CSSintermediate 9 min
relative, absolute, fixed and sticky explained, with the offset properties top, right, bottom and left.
How the position property lets you move elements out of the normal flow, and what each value does.
Badges on a card, a header that stays visible while you scroll, tooltips and pop-ups all rely on positioning.
Elements normally flow down the page one after another (position: static). The position property changes that:
relative: stays in the flow, but can be nudged with top, left, and so on, relative to where it would have been. It also becomes the reference point for absolutely positioned children.absolute: removed from the flow and placed relative to the nearest positioned ancestor (one with position other than static). If none exists, the page itself.fixed: placed relative to the browser window, and stays there when you scroll.sticky: acts like relative until you scroll past a point, then sticks like fixed.Offsets: top, right, bottom, left. Use z-index to decide which overlapping element is in front.
.card is position: relative, which makes it the anchor for its children..badge is position: absolute with top: -10px; right: -10px, so it pins to the card's top-right corner and sticks out slightly.overflow: auto, so it scrolls.position: sticky; top: 0. Scroll the box and it sticks to the top while the lines move beneath it.Move the badge to the bottom-left corner by using bottom and left instead.
absolute without a relative parent, so the element jumps to the page corner.absolute for layout. Prefer flexbox or grid.top: 0 on a sticky element, so it never sticks.relative, absolute, fixed, sticky change how an element is placed.absolute needs a positioned ancestor; offsets are top, right, bottom, left.Next: reusable values with custom properties.
<style>
.card {
position: relative;
width: 220px;
padding: 24px;
background: #f1f5f9;
border-radius: 8px;
}
.badge {
position: absolute;
top: -10px;
right: -10px;
background: tomato;
color: white;
padding: 4px 10px;
border-radius: 999px;
font-size: 12px;
}
.scroll {
height: 90px;
overflow: auto;
border: 1px solid #ccc;
margin-top: 20px;
}
.scroll h4 {
position: sticky;
top: 0;
margin: 0;
padding: 6px;
background: gold;
}
</style>
<div class="card">
Notebook
<span class="badge">New</span>
</div>
<div class="scroll">
<h4>Sticky heading</h4>
<p>Line 1</p><p>Line 2</p><p>Line 3</p><p>Line 4</p><p>Line 5</p><p>Line 6</p>
</div>