CSS Positioning
Absolute, relative, fixed, sticky, and stacking contexts.
Overview
Positioning controls element placement and layering.
Key Concepts
- Static — Default flow
- Relative — Offset from normal position
- Absolute — Relative to positioned ancestor
- Fixed — Relative to viewport
- Sticky — Hybrid of relative and fixed
Code Examples
/* Relative positioning */
.relative {
position: relative;
top: 10px;
left: 20px;
}
/* Absolute positioning */
.container {
position: relative;
}
.absolute-child {
position: absolute;
top: 0;
right: 0;
}
/* Fixed header */
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.page-content {
padding-top: 80px; /* Offset for fixed header */
}
/* Sticky elements */
.sticky-sidebar {
position: sticky;
top: 100px;
align-self: flex-start;
}
/* Centering with position */
.center-absolute {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Stacking contexts */
.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1000;
}
.overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 999;
background: rgba(0, 0, 0, 0.5);
}
/* Tooltip positioning */
.tooltip {
position: relative;
}
.tooltip-content {
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
z-index: 10;
}
/* Dropdown */
.dropdown {
position: relative;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 50;
}
/* Sticky table header */
.table-wrapper {
max-height: 400px;
overflow-y: auto;
}
.table thead th {
position: sticky;
top: 0;
background: white;
z-index: 1;
}
Practice
Build a sticky header with a fixed sidebar layout.