Understanding CSS Position
This post is a summary of the different values of the CSS
position property. It assumes you have knowledge of basic document flow.
position: absolute elements are removed from the normal document flow and will be positioned relative to their next parent with
absolute positioning up the element tree.
position:fixed elements are removed from the document flow and positioned relative to the browser window itself (the viewport). They will stay in their same position no matter what, even when scrolling.
position:static is the default position of all elements. It basically means that the element falls into the normal flow of the document. It is positioned relative to its parent. It won’t accept any box offset (
Position relative is very similar to static. A ‘relative’ element is placed exactly where a ‘static’ element would be placed, right in the document flow. There are three key differences:
- Box offset properties now work( top, right, bottom, left). Think of these as offsets from the element’s original position in the flow. For instance:
left:10pxwould move the element 10px to the left of it’s normal position in the document flow.
- The element now limits the scope of it’s child elements that are absolutely positioned. They are positioned in the context of this element. You have enabled something beautiful: “Relatively Absolute” layouts
Relatively Absolute Magic
When an element is given
position:relative a scope is created for it’s child elements. Elements within this scope that are
position:absolute will magically be placed in relation to the
position:relative parent. This unlocks a world of possibilities and the best part is that it’s very cross-browser.
I’ve found that often times when floats are used, the Relatively Absolute technique could be employed to make for a much simpler, less hacky, cross-browser solution. Chris Coyier has a great article on this.