Welcome to WebmasterWorld Guest from 184.73.8.127

Forum Moderators: not2easy

Message Too Old, No Replies

Need help centering a div.

Personal

   
3:49 am on Nov 11, 2007 (gmt 0)

5+ Year Member



If anyone has css-noob proof way to center the div's (i have 3 on my page), this would help.

feel free to <snip>(let me know)

[edited by: SuzyUK at 6:48 pm (utc) on Nov. 11, 2007]
[edit reason] no personal details thanks [/edit]

6:55 am on Nov 11, 2007 (gmt 0)

10+ Year Member



I usually use the negative left-margin trick.

Set up your container div class something like this.

.ctr {
position: relative;
margin-left: -50%;
left: 50%;
width: 50ems;
}
The effect of this is to push the left edge of the box to the exact middle of the page (left=50%), then pull it back by half the width off the container (-50%); thus exactly centering the box (div.ctr).
Setting the box size in ems works with any browser font size setting, and every browser (I Believe).

3:20 am on Dec 3, 2007 (gmt 0)

10+ Year Member



Hi twenty6ix

Thanks for the message, but I didn't see it till today. Responses need to be via the forum reply, or other readers will never get to see the response.

You said

Hi, you posted to my question about center a div, but I dont understand. ....If you could contact me on AIM at....

Put whatever you want to center in a box (DIV) and set its width and position. Like this:

<style type="text/css">

div.container {
width: 800px;
position: relative;
top: 20px;

Then center the left edge of the container on the page -

left: 50%;

Next, move the container left by half its own width -

margin-left: -50%; // or in this case, 400px.
}
</style>

The effect is to move the left edge of the container back by half its own width from the page center, thus exactly centering the page, no matter what width the screen is.

Next put your content in the div -

<div class="container">
Your nicely centered content entered in here
</div>

This is a proven cross browser method of centering page content.

Here is a shorthand way that only works with the newer browsers.

div.container {
margin-left; 20px auto;
}

3:25 am on Dec 3, 2007 (gmt 0)

10+ Year Member



Whoops, my BAD - Should read

div.container {
margin: 20px auto;
}

This give top and bottom margin of 20px and divides the left and right margins equally

R

[edited by: Rhys at 3:30 am (utc) on Dec. 3, 2007]

4:39 am on Dec 3, 2007 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



I don't like using that method unless it's absolutely necessary. It could cause potential problems if you're doing other more complicated things nearby (particularly in non-compliant browsers). Now perhaps there are virtually no problems which can arise by using it, but I still don't see the point, when you can just use margin: x auto, and for IE text-align center on parent.