CSS Position
What is Position in CSS?
The position property is employed to align an element in its parent element range.
Position Values:
Static Position (Default):
Elements are positioned according to the normal flow of the document.
div {
position: static;
}
Relative Position:
Positioned relative to its normal position.
div {
position: relative;
top: 10px; /* Move 10 pixels down from its normal position */
left: 20px; /* Move 20 pixels to the right from its normal position */
}
Absolute Position:
Positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* Center the element */
}
Fixed Position:
Positioned relative to the browser window.
div {
position: fixed;
top: 0;
right: 0;
}
This example fixes the element to the top-right corner of the window.
Sticky Position:
Acts like relative until it crosses a specified point, then it is treated as fixed.
nav {
position: sticky;
top: 0;
background-color: #f1f1f1;
}
This makes the navigation sticky at the top of the viewport when scrolling.
Z-Index:
The z-index property is often used in combination with the position property to control the stacking order of positioned elements.
div {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
This example sets the z-index of an element to 1, making it appear above elements with a lower z-index.
Notes:
- When an element is positioned, it can be moved using properties like top, right, bottom, and left.
- The relative positioning is often used for minor adjustments within the normal flow.
- absolute and fixed positioning remove the element from the normal document flow.