An element with relative
positioning remains within the flow of the document. Any additional positioning you provide will offset the element from this position.
An element with absolute
positioning is removed from the flow of the document, and is positioned with respect to its first nonstatic parent element.
So let's say you have the following HTML structure, and an accompanying fiddle:
<div class="awesomeParent">
<ul>
<li>First Piggy</li>
<li>Second Piggy</li>
<li>Third Piggy</li>
<li>Fourth Piggy</li>
</ul>
</div>
Now checkout the same fiddle, modified a bit using relative and absolute positioning. See the difference?
In the second fiddle, using relative positioning, the space where the third list element should be is preserved. It's only being offset by the additional top: 40px;
rule.
However, in the third fiddle, using absolute positioning, the space where the third list element should be is gone. In other words, that element is no longer in the normal flow of the document, and now the positioning rule top: 40px;
is with respect to it's first nonstatic parent. In this case, this is the div .awesomeParent
, which has a position: relative
. If no parent had been found, then the element would have been positioned with respect to the html
element. So in order to position an element absolutely within another element, you'll need to use position fixed, absolute or relative on the parent itself.
Images so you can compare the three:
