The CSS position property sets how an element is positioned within the document flow, allowing developers to offset elements using top, right, bottom, left, and z-index.
CSS supports five positioning modes:
.box-static { position: static; } /* Default flow */
.box-relative { position: relative; top: 10px; }
.box-absolute { position: absolute; top: 0; right: 0; }
.box-fixed { position: fixed; top: 0; width: 100%; }
.box-sticky { position: sticky; top: 0; }
Positioning modes explained:
static (Default): Normal document flow; ignores top/bottom/left/right/z-index.relative: Positioned relative to its normal position without removing it from document flow.absolute: Removed from document flow and positioned relative to its nearest positioned parent (an ancestor with relative, absolute, or fixed).fixed: Positioned relative to the viewport window; stays locked in place when scrolling.sticky: Toggles between relative and fixed based on the user's scroll position.flowchart TD
A["Positioned Parent (position: relative)"] --> B["Child Element (position: absolute)"]
B --> C["Child aligns relative to parent box edges (top: 0, right: 0)"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Position Demonstration</title>
<style>
.card-container {
position: relative; /* Relative parent binding */
background-color: #1e293b;
padding: 2rem;
border-radius: 8px;
max-width: 400px;
}
.badge-overlay {
position: absolute;
top: 12px;
right: 12px;
background-color: #059669;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8rem;
font-weight: bold;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<div class="card-container">
<span class="badge-overlay">NEW</span>
<h3>Pro Membership</h3>
<p>This card container uses relative positioning to bind the absolute badge overlay in the top right corner.</p>
</div>
</body>
</html>
position: relative on parents of position: absolute elements: Prevents absolute children from aligning to the root <html> viewport.position: sticky; top: 0; for persistent navigation bars: Keeps top navigation bars pinned to the screen top during page scrolling.z-index to manage stacking order: Manage overlapping layered elements using explicit z-index integers.Create a CSS class .sticky-header that stays pinned to the top of the browser screen during scrolling using position: sticky; top: 0;!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.