A common layout of websites is that the main content of the site does not take the entire width of the browser window and the content is centered on the page. For example, the content of the CNN site is fixed at 1000 pixels in width and centered. The content area can then be organized with sub-layouts or divided into multiple columns. This article describes how to center the HTML block elements on a page using two methods: using align attribute, and using CSS margin.

Using align Attribute

This method can be achieved using two nested div elements as shown in the code below. The first div sets the align attribute to "center". This will set the width of this element to 100% and center its content.

We may not want all the text inside this layout to be centered, so we have the second div inside the first one and resets the align attribute to "left".

<div align="center">
    <div align="left">
        Sub-layout and content of the page

Once we achieved centered layout, the second div can be further organized into sub-layout.

In addition, we can also use the <center> tag in place of the outer div. However, <center> is not support in the newer HTML5 standard.

Using CSS Margin

A block element can be centered by setting its CSS left and right margin to auto. This is often done using the shorthand margin property as shown below, where the first value sets the top and bottom margins, and the second value sets the left and right margins.

This code causes the browser to set the left and right margins to be the same width expanding the full width of the page and thus centering the content.

<div style="margin:0 auto; width:500px">
    Content to be centered

The following much be followed when using this approach:

  1. The div element must have a width.
  2. The div element must not float.