HTML and CSS Reference
Keeping It Centered
Many page layouts are based on centering objects either horizontally or vertically. You've
already learned how to horizontally center inline elements using the following style:
However, while this will center a block's contents, it won't center the entire block
itself. To do that, you set the left and right margin values to auto . For example, the fol-
lowing style rule horizontally centers every paragraph in a Web page while also setting
the top and bottom margins to 10 pixels:
margin: 10px auto;
Note that you must define the width of the block element or else the block will
assume the entire width of its container, making centering irrelevant.
There is no CSS style to vertically center a block element, but you can find sev-
eral workarounds on the Web to accomplish the trick. One approach is to create a
container element for the block and display that container as a table cell with the
vertical-align property set to middle . For example, to vertically center an h1 head-
ing, you could place it within a div container, as in the code
and apply the style rule
Note that this approach does not work with Internet Explorer versions before IE8
because those versions do not support the table-cell value for the display property.
You'll learn more about tables and table cells in the next tutorial.
Another trick for vertically centering a block element is to use the display property
to make the element into an inline element. You then can vertically center it by setting
the line height equal to the height of the container box itself. This approach has the
added benefit of enabling you to use the text-align property to horizontally center
it at the same time. The disadvantage is that the element is no longer a block and thus
may not be suitable as a container for other elements.
You'll examine one additional vertical centering technique in the next session on
absolute and relative positioning.
Working with Borders
Dan wants you to format the vertical navigation list so that each list item has a bottom
border; and when a user hovers the mouse pointer over the hypertext link, the back-
ground color of the entire length of the list item is highlighted (see Figure 4-37).