This is a blog that was created to talk about web design. The both of us hope people can learn from this, even learn something ourselves maybe.

Wednesday, December 22, 2004

How to center a div

Just a quick note on several methods of centering divisions. I'm sure that many of us know how to center a table (align='center') but divisions are slightly different. Firstly, there is no foolproof method, because of the different browsers and their varying levels of support for W3C standards.

1) Negative margins;

This relies on positioning the main division 50% across the page so the left side is in the center, and then changing the left margin to a negative value equal to the sum of half the width of the division, the thickness of the left padding of the division, and the thickness of the border on the left side (confusing eh?).


body {
margin: 0px;
padding: 0px;
}

div#main {
position: absolute;
left: 50%;
width: 600px;
margin-top: 50px;
margin-left: -316px;
padding: 15px;
border: 1px solid #000000;
background-color: #eeeeee;
}


In the above example, the main division is absolutely positioned 50% across the page, and then the left margin is set to -316px, ie. -((width/2) + left padding + left border) = -((600/2) + 15 + 1) = -316

2) Auto-Width margins;

This is the easiest of the two methods, but is unfortunately not directly supported by Internet Explorer. Never fear though, as there is a workaround built into this method in order to achieve the effect in the Microsoft browser.

It works by secifying the width of the central column of the page (in pixels or as a percentage) and by setting the margins of the column to an automatic value. In order to deal with the shortcomings of Internet Explorer, it is necessary to introduce a text-align: center; property to the body element. This, however, results in all of the text on the page also being centered, and so a text-align: left; is added to the CSS for the centered column.


body {
margin: 50px 0px;
padding: 0px;
text-align: center;
}

div#main {
width: 600px;
margin: 0px auto;
text-align: left;
padding: 15px;
border: 1px solid #000000;
background-color: #eeeeee;
}


In the above code, one division is used to contain the main text of the page and is given id="main" as an attribute.

4 Comments:

Blogger rrd said...

Ok I found out a couple of things by trial and error. Negative margins work well on absolutely positioned elements (perfectly, in fact).

7:43 PM

 
Anonymous Anonymous said...

Thank you!
[url=http://colvxcxi.com/vvjw/jlbi.html]My homepage[/url] | [url=http://qwkxshof.com/kbiz/ijlm.html]Cool site[/url]

7:58 PM

 
Anonymous Anonymous said...

Good design!
My homepage | Please visit

7:58 PM

 
Anonymous Anonymous said...

Nice site!
http://colvxcxi.com/vvjw/jlbi.html | http://wvanthza.com/batk/agbx.html

7:59 PM

 

Post a Comment

<< Home