Jul 27 2009

Centered Container divs

Category: Markup & Stylestephen @ 9:27 am

There are two com­monly used meth­ods of set­ting up a cen­tered main wrap­per (or con­tainer) div ele­ment on your web­site. Usu­ally, a web page will reside in one big div, sit­ting just inside the body tags, like so:

1
2
3
4
5
6
7
8
<html>
<head><title>My Site</title></head>
<body>
  <div id="container">
  ...
  </div>
</body>
</html>

This basic struc­ture makes it eas­ier to con­trol the page’s lay­out. By far, the most preva­lent method for styling the con­tainer looks a bit like the following:

1
2
3
4
5
6
7
8
9
body {
  text-align: center;
}
 
#container {
  margin: 0 auto;
  text-align: left;
  width: 960px;
}

In line 6, the con­tainer div’s left and right mar­gins are set to auto and its width set to 960 pix­els. This is the basis for cen­ter­ing the div on the page. There is another approach, which I found a bit cooler until just recently.

1
2
3
4
5
6
#container {
  left: 50%;
  margin-left: -480px;
  position: absolute;
  width: 960px;
}

This method doesn’t require giv­ing text-align:center to body and then over­rid­ing it imme­di­ately in the con­tainer div. I like that.

How­ever, a com­pli­ca­tion arrises when you want to put a back­ground image at the bot­tom of body; for exam­ple, a hor­i­zon­tal gra­di­ent. In this case, the best cross-browser way I’ve found to work is the first con­tainer cen­ter­ing method (using margin:0 auto). In addi­tion, the html and body tags will require some addi­tional styling to make it happen:

1
2
3
4
5
6
7
8
9
html {
  height: auto !important;
  min-height: 100%;
}
* html {height:100%} /* IE6 */
 
body {
  background: url(/images/bg-footer.png) repeat-x bottom;
}

The body style is obvi­ous, but it’s impor­tant to man­age the height of the par­ent html ele­ment as well, remem­ber­ing of course that IE6 does not sup­port min-height. Inci­den­tally, it’s also IE6 that is respon­si­ble for the text-align:center that we applied to body.

In con­clu­sion, don’t use the absolutely-positioned approach for styling your con­tainer. It’s cooler, but it just isn’t as robust as the stan­dard auto-margin method because it breaks out of the page lay­out (specif­i­cally, its html par­ent). For adding any back­ground image to the bot­tom, now or in the future, that is bad behav­ior. Stick margin:0 auto on your con­tainer and be done with it.

Share and Enjoy:
  • Twitter
  • del.icio.us
  • Google Bookmarks
  • Digg
  • Reddit
  • Technorati

Comments are closed.