A Quick Understanding of Absolute Positioning

This is by no means an exhaustive explanation of how absolute positioning works when trying to position block level elements in other block level elements. I will attempt to give a quick answer to a question I get a lot from new web developers: “Why isn’t this element where I want it?”

I’m of the opinion that absolute positioning should only be used on fixed content or graphical elements of a site that need special attention. For example, it could be used when a graphical flourish needs to fall outside of the normal flow of the document.

The easiest way to visualize this concept is by picturing every DIV as a box with no width or height (yet; we are going to give them dimensions in the CSS).

.container{
 width: 600px;
 height: 400px;
 position: relative;
 background: #444;
}
.innerContainer {
 width: 50px;
 height: 50px;
 position: absolute;
 top: 0px;
 left: 0px;
}
<div class="container">
 <div id="moveBox">
 </div>
</div>

The top and left positioning of the #moveBox element are set to 0. That means that the box will sit at its parent container’s (x,y) coordinate of (0,0). In order for this to be true, the parent container has to have its position set to “relative”. If this were not the case, #moveBox would then be positioned at the (0,0) of the next parent container up the DOM.

If you click the “Left: +” and the “Top: +” buttons below you will see the #moveBox div being positioned inside its parent container while it ignores the other elements inside the parent container.

Left: + Top: +

See what’s going on?

These block level elements are not getting pushed around or disturbed by the absolutely positioned div that is before them in the html. Absolute positioned elements ignore other block level elements. This allows you to position that element wherever you see fit inside the container (or outside if you use negative values).

I’m absolutely positioned. I will ignore other block level elements as you modify my top: and left: property.
top: 0
left: 0
Aug 14, 2011

Leave a comment