CSS Position
The position
property determines how elements are placed in the document. Values like static
, relative
, absolute
, fixed
, and sticky
give you control over element positioning, overlapping, and scroll behavior. Mastering positioning is crucial for creating sophisticated layouts and UI components.
Key Topics
- Static (default)
- Relative and Absolute
- Fixed and Sticky
Basic Example
position: absolute;
removes an element from the normal flow and positions it relative to its first positioned ancestor. position: relative;
keeps the element in flow, but lets you adjust its final position.
.container {
position: relative;
}
.overlay {
position: absolute;
top: 10px;
left: 20px;
background: rgba(0,0,0,0.5);
color: #fff;
padding: 5px;
}
Explanation: The .overlay
element is absolutely positioned within .container
. It’s removed from the normal flow, overlapping other elements as intended.
Fixed and Sticky
position: fixed;
attaches an element to the viewport, so it stays visible during scrolling. position: sticky;
behaves like relative until a certain scroll threshold, after which it sticks in place, perfect for headers or navigation bars.
Key Takeaways
- Layering: Positioning affects how elements overlap.
- Scrolling: Fixed and sticky positions enhance navigation.
- Control: Relative and absolute positioning help fine-tune layouts.