View Full Version : element centring without known width

05-26-2010, 12:11 AM
I am writing a CMS. I need a text block element to align in the centre with the text inside aligned left. Because it is a CMS there is no way of knowing how much content is in the element so I cannot set a width.

If there is only one word it needs to be in the middle and if there are paragraphs they need to have the text aligned left and expand to the width of the containing div.

The element needs to collapse on the content. I can do it with tables but can't figure out how to do it without tables. Although I'm not sure why tables are so bad but they seem to be frowned upon and I'd love to conform. Is it possible?

This does exactly what I want:
<table style="margin: 0 auto"><tr><td>sldmnfkj</td></tr></table>


<table style="margin: 0 auto">
kjh kjhkjh<br>
sfldkj sdlfkj lsdfkj sldfkj<br>

I'm using PHP's nl2br() for the line breaks.

05-26-2010, 12:36 AM

You are on the correct path there with the use of tables, so what you would actually do is set the block element to display:table-cell or display:table; and then margin:0 auto;

But this causes a problem within IE7/6 because they do not understand display:table; properly..so you must use conditional comments for IE7/6 and then use display:inline; and zoom:1; on the block element with text-align:center; on it's container..

There is another method if the DIV is floated using positioning but I can't find it right now...

Anyhow from the CMS you could accept a user-defined paramter for the width of this DIV anyway then apply it to the element and just use margin:0 auto; as normal...Because if you think the text is always going to end up stretching to 100% width eventually, so it would be an odd effect otherwise as only a small amount of content would result in it not filling the entire width.

05-26-2010, 01:07 AM
Thank you very much. I didn't know about display: table

That does it.