Skip to: Navigation | Content | Sidebar | Footer


Weblog Entry

Centering Absolutely Positioned CSS

April 23, 2003

When it comes to absolute positioning, you are stuck aligning everything to the left or right of the browser. There is no way to align from a center axis.

I was faced with that a few days back, and it turns out it’s entirely possible, actually, given a bit of monkey work. Here’s my solution, which holds up in everything I’ve checked it in so far.

It strikes me that there’s a simpler way to do it, but the example I’m working with hasn’t duplicated when simplified. I’ll update if I manage to get it.

update: IE5-friendly example added.


Reader Comments

haze says:
April 23, 04h

ns4 + tables + transparent spacer gifs + limitations + browser compatibility issues + quirky bugs = the old method

CSS + divs + limitations + browser compatibility issues + quirky bugs = the new method

i like how CSS has progressed and i do admit that CSS has provided a stronger element for the web browsing experience… but is it the light at the end of the dark tunnel? helllllll-no. far from it. ;0)

paul says:
April 23, 04h

maybe i’m missing something, but for centering div’s with xhtml, i just put a div align=center tag around everything i want centered, and it works fine (view source on my twothirty.com site to see what i mean).

Dave says:
April 23, 05h

haze - by your count, that’s 6 to 5. Score one for CSS. ;)

paul - yeah, that works for documents built in a sequential 1-2-3 order, where you’re working from the top down and positioning elements according to their place in the code. If you start positioning non-linearly, it’s almost impossible to break out of that flow given the dynamic nature of the content in each element. This is, I believe, why all the examples of the standard 3 column layout are built to scale the entire browser window. (of course, in researching that statement I found Eric Costello’s example of a fixed-width, centered 3 column layout, proving me wrong)

Anyway, a scenario. You’ve got a list of links that’s running down the right side of the screen. You’ve been a good little web developer and floated the containing DIV, so things are fine. Now you’re asked to take that list, and run it horizontally across the header. The easiest thing to do would be to throw it in the top, positioned absolutely, but you can only do that if your content isn’t floating. If your site is fixed-width, centered, you have almost no way of using absolute positioning, so you’re SOL.

Not a very likely occurance, so this is mostly an academic exercise, but I did need to do precisely that the other day.

haze says:
April 24, 11h

5 to 6? that depends on whether youre willing to support ns6 i guess. lol! i’m not, but i know ESPN does.