📍 Position = Layout Control
Elements need precise positioning. Position property controls layout. Static, relative, absolute, fixed, sticky.
📝 Position Types
/* Static (default) */ position: static; - Normal flow - No positioning /* Relative */ position: relative; - Relative to normal position - Offset with top, right, bottom, left - Other elements not affected /* Absolute */ position: absolute; - Removed from flow - Relative to nearest positioned ancestor - Or relative to document /* Fixed */ position: fixed; - Removed from flow - Relative to viewport - Stays in place on scroll /* Sticky */ position: sticky; - Hybrid of relative and fixed - Sticks when scrolling - Great for headers
🎯 Practical Examples
/* Modal (fixed) */
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 1000;
}
/* Header (sticky) */
.header {
position: sticky;
top: 0;
background: white;
z-index: 100;
}
/* Tooltip (absolute) */
.tooltip-container {
position: relative;
}
.tooltip {
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
}
/* Overlay (fixed) */
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 999;
}
/* Dropdown (absolute) */
.dropdown {
position: absolute;
top: 100%;
left: 0;
min-width: 200px;
background: white;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* Sidebar (fixed) */
.sidebar {
position: fixed;
top: 0;
left: 0;
width: 250px;
height: 100%;
background: #333;
}
/* Centered element (absolute) */
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
💡 Position Tips
- Use relative for positioning context
- Use absolute for overlays
- Use fixed for modals and headers
- Use sticky for section headers
- Use z-index with positioned elements
“Position property controls layout. Static, relative, absolute, fixed, sticky. Essential for CSS layouts.”
