18. Example: Centering, the CSS way

18. Example: Centering, the CSS way

The text-align property aligns text, but does not affect box position or width. See how the box expands to the full width of its container (the window, in this case).

<div style="
text-align: center; border: 1px solid red;">

What if we want the box to be centered, but the text inside it to be left-aligned? Explicitly setting the width prevents the box from filling the window, and allows us to center with margin: auto.

<div style="
width: 20em; margin: auto; border: 1px solid red;">

Of course, guessing at the correct width is impossible. Using display: table on the block makes the block "shrink-wrap" around its content, so we don't need to know its width.

<div style="
display: table; margin: auto; border: 1px solid red;">
Ken Keys, CAIDA, 2006-12-01