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 ...

Get CSS Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.