GeekZilla
Centering a DIV using the negative margin method
The following CSS will center a DIV whih is 500px wide. This method is very clean and works in all browsers.
div { position: absolute; left: 50%; width: 500px; margin-left: -250px; }
Change the width to suit your needs then change the margin-left to half the width of the div.
Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.
Paul is the COO and co-founder of kwiboo (http://www.kwiboo.com/) and is also the creator of GeekZilla.
Comments
John S.
said:
Is there some reason margin { 0 auto; } doesn't work?
Brennan Stehling
said:
How about when width is 100%?
phayman
said:
Why would you want to center a div which was 100% wide? Surely it would fill the screen anyway?
Brennan Stehling
said:
Sorry, I typed that too fast. I meant a percentage, like 70%. Many times I have a fluid layout so I do not know the width. Previously I have resorted to using Javascript to adjust the CSS rules to auto-correct browser differences. I also resort using text-align for the browsers that treat blocks like inline text.
TweeZz
said:
I think what Brennan meant was that what if the parent element has width:100%, but the div itself let's say 100px;
How do you get that div to center in the parent element?
John S.
said:
Brennan,
<div style="width: 70%; margin: 0 auto; height: 300px; background-color: #f00;">centered</div>
Mike K
said:
Handy! Works a treat! Thanks
Sam
said:
Paul, you are my hero. What a gem of simple information rather than being forced into using relative positioning with auto margins.
Adam Bell
said:
Cheers for that div - worked like a treat.
asedt
said:
I dont like this method, if the window size is below the width the content gets otside the window so you cant srcoll to it. I don't know any workaround for that. So i prefer any margin: 0 auto + IE text-align: center fix or liqid design with margin: 0 10% or exual method.
Nick Rosener
said:
Thank you so much! I have been researching this for a long time, and this method works very well.
-Nick Rosener
Tech Nick Consulting
Peter
said:
Man, this is the most brainy solution to my problem. I mean this works when a div is wider than the browser window or screen. I was very frustrated for not being able to solve this without Javascript.
Bradley T
said:
OMG!!! Thank YOU!
I have also been looking for a long time for a simple solution for this. It works perfect for my needs. No javascrip, No jquery.
Just simple, simple, CSS.