Position in CSS
? position in CSS
The position property specifies how an element is positioned in the document. It affects how the element is laid out and how it moves relative to its normal flow, its containing block, or the viewport.
Values
| Value | Description |
|---|---|
static | Default. The element is positioned according to the normal document flow. |
relative | Positioned relative to its normal position; can be shifted with top, left, etc. |
absolute | Positioned relative to the nearest positioned ancestor (not static). Removed from normal flow. |
fixed | Positioned relative to the viewport; stays fixed during scrolling. Removed from normal flow. |
sticky | Acts like relative until a threshold scroll position is reached, then behaves like fixed. |
How to Use
.element { position: relative; /* or absolute, fixed, sticky */ top: 10px; left: 20px;}Detailed Behavior
| Position | Effect | Removed from Flow? | Reference Point |
|---|---|---|---|
| static | Default, normal document flow | No | N/A |
| relative | Moves relative to original spot, leaves space | No | Original position |
| absolute | Positioned relative to nearest positioned ancestor | Yes | Nearest ancestor with position ? static |
| fixed | Stays fixed relative to viewport | Yes | Viewport |
| sticky | Toggles between relative and fixed based on scroll | No (mostly) | Nearest scrollable ancestor or viewport |
Example: Relative
.box { position: relative; top: 10px; /* moves down 10px from normal spot */ left: 20px; /* moves right 20px */}Example: Absolute
.container { position: relative;}.child { position: absolute; top: 0; right: 0;}Here .child is positioned at the top-right corner of .container.
Example: Fixed
.header { position: fixed; top: 0; left: 0; width: 100%; background: white;}Sticky header stays visible on scroll.
Example: Sticky
.navbar { position: sticky; top: 0; background-color: yellow;}Navbar sticks to the top when scrolling past it.
Want me to provide interactive examples or explain stacking context with z-index?