Properly Centering a DIV

During the development of a scenic designers web site, I came across something I didn't expect to be an issue. What is required is a div with the following properties:

  • a set width and height
  • vertically and horizontally centered in the browser window
  • correctly displayed on both FireFox and Internet Explorer (these as the browsers most used with the site)
  • repositions itself as the browser window changes size

The most obvious solution would be to use auto margins. By setting the container of the div using min-width the margins would automagically keep the div centered (well it should but Internet Explorer once again proves that M$ can't read and required a hack using text-align). Unfortunately this only works to align horizontally.

The best solution to this that I could find was to set the absolute position of the div with left and top set to 50%. However this is only half the story because this will set the top left of the div to the center of the screen. To correct for the width and height of the div appropriate margins are set. An example is shown below:

div.container {
     position:     absolute;
     left:         50%;
     top:          50%;
     width:        600px;
     height:       400px;
     margin-left:  -300px;   /* Must be half the width */
     margin-top:   -200px;   /* Must be half the height */
}

- FIN -


About this entry