Positioning
The CSS position property allows you to control how and where elements are placed on a web page. It defines whether an element should follow the natural flow of the document or be positioned at a specific spot using coordinates like top, right, bottom, and left.
Positioning is one of the most powerful features in CSS because it lets you create layouts, fixed headers, sticky navigation bars, tooltips, modals, and much more.
Syntax
selector {
position: value;
top: 10px;
left: 20px;
}
Static (Default)
By default, all elements have position: static;. They follow the normal document flow without any special positioning.Relative
Elements are positioned relative to the normal position in the document.
You can use the top, right, bottom, and left properties to move the element from its original position.
Syntax:
selector {
position: relative;
}
- Absolute Elements are positioned relative to the closest positioned ancestor (parent), which means we need to have a parent element with a positioning other than 'static'.
Note: An absolutely positioned element is removed from the normal flow.
Fixed
An element with position: fixed; is positioned relative to the viewport (the screen itself). It does not move when the page is scrolled.
This is useful for creating elements like fixed headers or footers.Sticky
Position sticky is a hybrid between 'relative' and 'fixed'.
It allows an element to become "stuck" to the top or bottom of its container when scrolling, but it behaves like relative positioning within the container until it reaches a specified offset.
Float
Although not a position value, the float property is often used alongside positioning to wrap text around images. For more details, follow CSS Float.
Quick Recap
Static → Default (normal flow).
Relative → Moves element relative to its original spot.
Absolute → Positioned relative to nearest ancestor with positioning.
Fixed → Stays fixed to the viewport, even on scroll.
Sticky → Behaves like relative until a threshold is reached, then sticks.
Float → Used for text wrapping (not an actual position type).
Z-Index
When there are multiple overlapping elements, the z-index helps in deciding the order of their visibility. The element having the highest value of z-index is shown first, followed by the other elements.
Syntax
selector {
position: relative | absolute | fixed | sticky;
z-index: value;
}
z-index value can be:
Positive integer (e.g., 1, 10, 100) → Higher numbers appear above lower ones.
Negative integer (e.g., -1) → Pushes the element behind others.
Auto (default) → Follows the natural stacking order.
Note: The z-index property only works on positioned elements (relative, absolute, fixed, sticky).
Default Stacking (Without z-index)
If you don’t specify a z-index, elements stack based on HTML order:
The element written later in the HTML appears on top.
In the above example, Box 3 would cover the others by default if no z-index was applied.
Top comments (0)