O'Reilly logo

CSS Cookbook by Christopher Schmitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.3. Centering Elements on a Web Page

Problem

You want to center parts of a web page, as in Figure 2-5.

The headline text centered

Figure 2-5. The headline text centered

Solution

To center text in a block-level element, use the text-align property:

h1, h2, h3 {
 text-align:center;
}

Discussion

By using text-align, you can center text inside block-level elements. However, in this example, the heading takes up the entire width of the body element, and if you don’t apply a background color to the element, you probably won’t even notice this is happening. The gray background color in Figure 2-6 shows the actual width of the centered elements.

The actual width of the elements shown by the gray background color

Figure 2-6. The actual width of the elements shown by the gray background color

An alternative approach is to use margins to center text within its container:

h1, h2, h3 {
 margin-left: auto;
 margin-right: auto;
}

When you set the margin-left and margin-right properties to auto, you center the element inside its parent element. However, older but still popular browsers won’t render the presentation correctly. So, workarounds are needed for individual situations.

Tables

To center a table, place the table as the child of a div element:

<div class="center"> <table width="50%" border="1" cellpadding="30"> <tr> <td>This is the first cell</td> <td>This is the second cell</td> </tr> <tr> <td>This ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required