Thursday 27 September 2007

Text-align: center;

How do you centre-align something using CSS?

Here is my first attempt - there is a container DIV (parent) to specify the centre-alignment and a content DIV (child) with a red background and some text inside:
<div style="text-align: center; width: 100">
<div style="background-color: red; padding: 10px; text-align: left; width: 50%;">
Hello World
</div>
</div>

This only seemed to work in IE; Firefox, Opera and Safari still rendered it on the left. Adding margin: auto to the content DIV fixed the problem in all browsers:
<div style="text-align: center; width: 100%">
<div style="background-color: red; margin: auto; padding: 10px; text-align: left; width: 50%;">
Hello World
</div>
</div>

No comments: