Understanding Relative Positioning in CSS

One aspect of CSS that can be a bit confusing (not that there aren’t plenty of those) is relative vs absolute positioning. It really seems a bit backwards at first.

Suppose you have the following code:

#container {
position: relative;
}

You might think this means that you’re not positioning container relative to something else, but in fact it means that other boxes inside container can be positioned relative to it. If you give absolute positioning to elements inside container, they’ll now have an absolute position relative to the container. Confusing enough? Consider this example:

#badlynamedbox {
position: absolute;
top: 0;
left: 0;
}

Badlynamedbox will now appear in the upper left corner of the container, not the brower window (although it’s possible these could be the same). Very useful! More formally, an absolutely positioned element will be positioned relative to the first relatively positioned ancestor; if there are no ancestors that are explicitly defined to be relatively positioned, this will be the html element.