December 10, 2008

CSS Absolute and Relative positioning – explained

Filed under: Tips — Tags: — Webopius @ 1:51 pm

I’m going to pick a statistic out of thin air and say that at least 80% of CSS tutorials describe absolute CSS positioning incorrectly. Now I’ve written that I’d better try and get it right here!

What most tutorials say

When covering absolute positioning, most CSS tutorials will say something along the lines of this:

“To position an element at a specific location on your page, use absolute positioning. For example, to position an element 54 pixels from the top of the page and 23 pixels from the left, use this CSS: {position: absolute; top: 54px; left: 23px; }

Well, that’s not quite accurate, at least for elements that have a positioned parent element

Correct Absolute Positioning

The correct description of absolute positioning is a bit more complex and probably why many authors can’t get it to work correctly so float away their divs left and right without using any kind of positioning at all.

In my words, this is how absolute CSS positioning should be described:

Absolute positioning allows you to position an element relative to it’s nearest positioned parent element. If no such parent element exists then the html or body element is used (depending on the browser).

Yes, that’s right, absolute positioned elements are relative. Confused?

All this means is that if any containing parent element is positioned (has it’s position:relative or position:absolute), then a child element with a position of absolute will be placed relative to this parent.

Text flow for absolute positioned elements

One final gotcha for absolute positioned items is that once an element is positioned using the absolute setting, then content will flow to fill the space where that element would have been before it was positioned.

This is actually quite helpful and can be used for some neat effects. For example, the image you see to the right of this article is actually contained within the body of this article’s text. But, it is wrapped in a blockquote that has an absolute position. This moves the image to the right and the text of the article moves up to fill the space it vacated.

Relative Positioning

After all that head scratching with absolute positioning, relative positioning is actually very straightforward.

A relative positioned element is positioned relative to where it would have been if no positioning was used

Also, unlike absolute positioning, content does not fill the space vacated by a relative positioned element.

  • Tags