Centering a div in the window

Posted: 2008-07-10 04:55:21, Updated: 2009-07-28 21:52:22

Ever wanted to center a panel in the middle of the browser window? There's a lot of code out there that claims to do this, but it isn't standards compliant and doesn't work on all browsers. But never fear, there is an easy way to do it without any browser specific hacks.

First, you need a couple of styles:

body {
  background-color: #000000;
}

.reference {
  background-color: transparent;
  position: absolute;
  top: 50%;left: 50%;
  width: 1px;height: 1px;
}

#panel {
  position:absolute;
  left:-485px;top:-256px;
  width:970px;height:512px;
  background-color:#FFFFFF;
}

Now the html:

<div class="reference">
  <div id="panel">
    Your content here
  </div>
</div>

The reference style creates a 1px by 1px div centered in the middle of the window. Inside this div is the panel. Normally this would place the upper left hand corner of the panel in the center of the window. To correct for this, the left and top properties are set to -(width/2) and -(height/2) respectively. Since the width and height of the panel is known these can be hard coded into the styles.

Happy Hacking