Horisontal CSS Centering for Absolute Positioning

April 6th, 2005 by Joen ,

A new and better way to center your elements horisontally has been found. Read all about it on AkaXakA’s website.

In my daily work, I needed to center a div horisontally. Usually this is easy. Not so when using absolute positioned elements.

Basically, absolute positioning allows you to type in coordinates for your div, coordinates from the top-left of the screen.

I found the following solution to work fairly well, and I’m posting it here in case someone else might gain from it, as well as a reminder to myself.

Give then Take

If you need to center your absolutely positioned #content div, wrap it in a new #content-container div and apply the following CSS.

#content-container {
	width: 500px;
	position: absolute;
	left: 50%;
}
#content {
	position: absolute;
	left: -250px;
}

This will move the #content-container div’s left side to the exact center. After that, the #content div will be moved half the width of the #content-container div’s width to the left, thereby centering it.

It works reasonably well in both Mozilla and IE, as long as the browser is larger than the centered content.

Update: Doesn’t work as well as I initally thought. If scale the browser to be smaller than the the width of the #content-container, it’ll bork. Suggestions are welcome.

Update: AkaXakA’s method is better. Read it in the comments.

Feel free to post your solutions in the comments.


Websites linking to this post:

  1. aarohi johal » Horizontal CSS Centering for Absolute Positioning
  2. On Horisontal CSS Centering using Absolute Positioning

Comments (45)

  1. Harley C. Dangan says:

    OMG! I was having this alignment problem with absolute divs for days! This really helped me a lot!!!

    Cheers to you!

    Quote

  2. Chad (subscribed) says:

    I'm centering a transparent png logo on top of my header page using the absolute positioning. You have the right method, for the #content just replace the "px" with an elastic "em" and it will work both on IE and Firefox. It works absolutely fine on mine.

    Thanks and more power!!

    Quote

  3. Spirt Bear says:

    Thanks so much. Lina's code did the trick for me to enable me to display some progress bars that appear while a simulation is crunching away, than using the code I could cover up those progress bars once the simulation was finished and results could be displayed as if a new page is being rendered.

    Quote

Comment

(required)

(required)

Textile

Textile is a method that uses simple symbols to quickly write rich text markup. These are the most common:

  • _emphasis_
  • *strong*
  • -deleted text-
  • !imageurl.gif!