How to centre a block element on the page using CSS

In the past I’ve always used the following CSS code to centre a DIV (or other block element) on a page.

#divid {
  width: 620px;
  left: 50%;
  margin-left: -310px;
}

It works by setting the left edge of the div at 50%, which if it containing element is BODY then we are setting the left edge to 50% of the page. If we left it at that then the DIV would start at half way and not be centred at all. The trick is to set the left margin “margin-left” to be negative half of the DIV’s width. This forces the DIV back towards the left by half and therefore you end up with a DIV centred on the page.
Another method is to use the following.
#divid {
  width: 620px;
  margin-left: auto;
  margin-right: auto;
}

As indicated in the W3C CSS specification, which can be found here:
If ‘width’ is set to ‘auto’, any other ‘auto’ values become ‘0’ and ‘width’ follows from the resulting equality.
If both ‘margin-left’ and ‘margin-right’ are ‘auto’, their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

This basically says that your DIV must have a width otherwise the margins are set to 0, but if it does have a width then the margins are equal and the DIV is centred.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks

1 thought on “How to centre a block element on the page using CSS

  1. Pingback:Frank MacDonald » How to centre a block element on the page using CSS Red Mars …

Leave a Reply

Your email address will not be published. Required fields are marked *

*