CSS Crib sheet #3 - Centering a Div | February 4, 2004
I often see people posting on CSS discussion lists to ask how to centre a div. It's actually very simple, although you need to use a few hacks for unruly browsers.
body {
text-align: center;
min-width: 600px;
}
#wrapper {
margin:0 auto;
width:600px;
text-align: left;
}
To centre the div, simply set its width and then use margin auto on the right and left hand sides. Unfortunately this doesn't work in IE. However luckily for us, IE also misinterprets text-align: center. Applying this to the body centres the div in IE. However it also centres the body text in all the other browsers as well. To get round this you need to use text-align: left; on the div that you're centering.
This gets IE up to scratch. However this is the step I always forget. In Mozilla, if you reduce the size of the browser window, half of your centred div hangs off the left of the page. This is an odd one, but I've been reliably informed that it's the correct behaviour. To prevent this, just set a min-width on the body tag.
Posted at February 4, 2004 8:02 PM
ste said on February 4, 2004 10:59 PM
Hrm, I knew all of that except the min-width bit. Hrm, guess I’ll have to start adding that on sites where I center fixed-width content. And I guess I should add resizing my windows so that they are smaller than the content area to my testing regimen - I never even noticed that problem. (I usually only resize to the typical 580×420 size that is roughly equal full-screen 640×480 with browser chrome.) Thanks!