An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling. Here is a simple example:
HTML file: | Displayed by browser: |
---|---|
<style>
div.relative { position: relative; width: 400px; height: 200px; border: 3px solid #8AC007; } div.absolute { position: absolute; top: 80px; right: 0; width: 200px; height: 100px; border: 3px solid #8AC007; } div.absolute2 { position: absolute; top: 80px; right: 225px; width: 150px; height: 200px; border: 3px solid #8AC007; } </style> <body> <div class="relative">This &lt;div&gt; element has position: relative; containing a child element that has been absolutely positioned. <div class="absolute">This &lt;div&gt; element has position: absolute; and is inside a parent element which is relatively positioned.</div> <div class="absolute2">This &lt;div&gt; element has position: absolute; and although not contained by the relative element, it is positioned relative to it.</div> </div> </body> |
This <div> element has position: relative; containing a child element that has been absolutely positioned.
This <div> element has position: absolute; and is inside a parent element which is relatively positioned.
This <div> element has position: absolute; and although not contained by the relative element, it is positioned relative to it.
|
Note: A "positioned" element is one whose position is anything except static.