In several of the popup examples on the absolute positioning page the "positioned ancestor element" was styled with position:relative
but it was not offset from its default position in the normal flow of the document. On this page we will explore what happens when we do move a relatively positioned element out of its default position in the normal flow.
Relative positioning begins with the styled element box in the normal flow of the document. Like absolute and fixed positioning, a relative position element uses left
, top
, right
, and bottom
properties to tell the user agent how far to offset the element box from the specified edges of the space the element would occupy in the normal flow if it were not positioned.
An analogy for relative positioning is that it behaves like a foot and a footprint in the sand. The foot (HTML element box) creates the footprint (occupied space in the normal flow of the document). But the foot (element box) can then be offset by some distance from, but relative to, the footprint. The void space of the footprint remains; a relatively positioned element's original space in the flow of the document is maintained while the visible contents are offset.
Let's take a look an an Example.
In the discussion on absolute positioning, I presented this Example which shows a relatively positioned ancestor element, which has not been offset from its position in the normal flow, and its absolutely positioned nested element. Let's now examine what happens when the relatively positioned ancestor element IS offset from the normal flow and what the effect is on an absolutely positioned nested element.
In this Example the relatively positioned ancestor element is now given offset values of top:30px
and left:30px
. The absolutely positioned nested element maintains its established offset from it's positioned ancestor which is top:90px
and left:40px
. When you compare it to the popup example in the previous paragraph you can see that the absolutely positioned nested element has also shifted 50 pixels to the right and down in tandem with the new offset values assigned to its relatively positioned ancestor element.
Relatively positioned boxes can be useful as well as decorative. As containing blocks, a relatively positioned element provides a positioning reference to any absolutely positioned child element. By leaving the top, bottom, left and right properties at their default value of 0 and setting the position property to relative, a box will be displayed at its original position, still take up space in the document flow, but also define a new set of co-ordinates for its absolutely positioned children. We will use this capability later in layouts.