CSS trick
18 December 2008

I learned a CSS trick today - centering an absolutely positioned div. It is quite simple, really. Set top to 50% and set the left-margin to a negative value of half of it's width.

For example:

#centered_div {
  position: absolute;
  width:500px;
  top: 0;
  left: 50%;
  margin-left: -250px;
}

Cleverly simple.

Comments:
J-othy @ December 18, 2008 09:30
Nice. You can centre stuff vertically too, using top: 50% and margin-top: -{half the height} as well. The unfortunately ugly and neglected homepage of Jeffothy.com has used this trick for ages.