January 12, 2011

Center div horizontally

Question by Don

On this page, I would like to horizontally center the main #container div relative to the page. Normally I would achieve this by adding a CSS rule,

#container { margin: 0 auto }

However, the layout of this page (which I did not write), uses absolute positioning for #container and most of its child elements, so this property has no effect.

Is there any way I can achieve this horizontal centering without rewriting the layout to use static positioning? I’ve no problem with using JavaScript/JQuery if that’s the only way to achieving my objective.

Answer by Starx

Same as @rquinn answer but this will adjust to any width. Check this demo

http://jsfiddle.net/Starx/V7xrF/1/

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!