CSS Position
The position property in CSS specifies how an element is positioned in the document.
It controls whether an element is placed relative to its normal flow, its parent, or the viewport.
Position Values
Common position property values include:
static: Default value; the element follows the normal document flow.relative: The element is positioned relative to its normal position.absolute: The element is positioned relative to the nearest positioned ancestor.fixed: The element is positioned relative to the viewport and does not move on scroll.sticky: The element toggles between relative and fixed depending on scroll position.
Static Position
Static is the default positioning; elements appear in normal flow.
div {
position: static;
}
Relative Position
Relative positioning moves an element relative to its normal position.
div {
position: relative;
top: 10px;
left: 20px;
}
Absolute Position
Absolute positioning removes the element from normal flow and positions it relative to the nearest positioned ancestor.
div {
position: absolute;
top: 50px;
right: 20px;
}
Fixed Position
Fixed elements are positioned relative to the viewport and remain in place when scrolling.
header {
position: fixed;
top: 0;
width: 100%;
}
Sticky Position
Sticky elements behave like relative until a certain scroll position is reached, then they become fixed.
nav {
position: sticky;
top: 0;
}
Best Practices for Position
- Use
relativefor small offsets and adjustments - Use
absoluteinside a positioned parent for precise placement - Use
fixedfor headers, footers, or floating elements - Use
stickyfor menus or sections that should remain visible while scrolling
Common Mistakes with Position
- Forgetting to set a parent element as
relativewhen usingabsolutepositioning - Overusing fixed elements that interfere with page flow
- Not considering responsive layouts when positioning elements
position with z-index can control element
stacking order for better layout control.