Index 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

O'Reilly logo

Techniques for Centering Elements on a Web Page

Problem

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

Solution

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

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

Figure 5-8. The headline text centered

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 5-9 shows the actual width of the centered elements.

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

Figure 5-9. 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;
 width: 300px;
}

When you set the margin-left and margin-right properties to auto (along with a value for the width property), you center the element inside its parent element.

Tables

To center a table, set a class attribute with a value:

<div class="center"> <table> <tr> <td>This is the first cell</td> <td>This is the second cell</td> </tr> <tr> <td>This is the third cell, it's under the first cell</td> <td>This is the fourth cell, it's under the second cell.</td> </tr> ...

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