Positioning
CSS Position Relative
Relative Positioning in CSS
CSS position relative offsets elements, with z-index for stacking.
What is CSS Position Relative?
CSS position: relative;
is a positioning property that allows you to offset an element from its original position in the document flow. Unlike absolute positioning, relative positioning keeps the element in the normal document flow, but you can use properties like top
, right
, bottom
, and left
to adjust its position relative to where it would normally be.
How Relative Positioning Affects Layout
When an element is given a position: relative;
, it remains in the flow of the document. Other elements around it will behave as if the relatively positioned element has not moved, which can create interesting layout effects. This behavior is particularly useful for making slight adjustments to the element's position without affecting the layout of surrounding elements.
Understanding Z-Index with Relative Positioning
The z-index
property is often used with position: relative;
to control the stacking order of overlapping elements. A higher z-index
value means the element will be on top of others with lower values. Note that z-index
only works on positioned elements (those with position
set to anything other than static
).
Practical Example: Offset and Stack Elements
Let's consider an example where two boxes are positioned relative to their normal position. One is offset slightly, and they both have different z-index
values, affecting their stacking order.
In this example, Box 2 will appear on top of Box 1 due to its higher z-index
value. Both boxes are slightly offset from their original positions, demonstrating the effect of position: relative;
.
Positioning
- Position Relative
- Position Absolute
- Position Fixed
- Position Sticky
- Z-Index
- Previous
- Multi-Column
- Next
- Position Absolute