Horisontal CSS Centering for Absolute Positioning
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.
- The Wild West
- Horisontal CSS Centering for Absolute Positioning
- April '05 Installment: Pointless
- Copenhagen Cycling Culture
OMG! I was having this alignment problem with absolute divs for days! This really helped me a lot!!!
Cheers to you!
Quote
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
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