When using relative
positioning for an element, it will stay within the document's flow. Any additional positioning applied will move the element from its original position.
On the other hand, with absolute
positioning, the element is taken out of the normal document flow and positioned in relation to its first non-static parent element.
For example, consider the following HTML structure along with a related demo:
<div class="awesomeParent">
<ul>
<li>First Piggy</li>
<li>Second Piggy</li>
<li>Third Piggy</li>
<li>Fourth Piggy</li>
</ul>
</div>
By comparing the fiddles with relative and absolute positioning, you can observe the differences.
In the relative positioning fiddle, the space where the third list item should be remains, but it is offset by the top: 40px;
rule.
However, in the absolute positioning fiddle, the space for the third list item disappears. This means that the element is no longer part of the regular document flow, and the positioning is now based on its nearest non-static parent element, which in this case is the .awesomeParent
div with position: relative
. If no suitable parent is found, the positioning would default to the html
element. To position an element absolutely within another, the parent must have a fixed, absolute, or relative position.
Visual aids are included below for comparison: