You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

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.

kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Hayman Skype
Author : Paul Hayman
Published : Thursday, 21 June, 2007

Paul is the COO of kwiboo ltd consultant and has more than a decade of 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?

June 21, 2007 - 6:55 PM

Brennan Stehling said:

How about when width is 100%?

June 21, 2007 - 7:00 PM

phayman said:

Why would you want to center a div which was 100% wide? Surely it would fill the screen anyway?

June 21, 2007 - 7:31 PM

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.

June 21, 2007 - 10:22 PM

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?

June 22, 2007 - 4:58 AM

John S. said:

Brennan,

<div style="width: 70%; margin: 0 auto; height: 300px; background-color: #f00;">centered</div>

June 22, 2007 - 7:02 PM

Mike K said:

Handy! Works a treat! Thanks

June 27, 2007 - 5:37 PM

Sam said:

Paul, you are my hero. What a gem of simple information rather than being forced into using relative positioning with auto margins.

October 02, 2007 - 1:56 AM

Adam Bell said:

Cheers for that div - worked like a treat.

July 15, 2008 - 12:22 PM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views