Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Appropriate Way to Center Content

I prefer working with CSS based design, but as more of a back end coder my CSS skills are a bit weak. When I get involved with layout, I tend to fall back on table based formatting because my mind has been warped by years of table based abuse. There's one particular problem that I always trip over. What is the best CSS alternative to:

<table width="100%">
    <tr>
        <td align="center">
            content goes here
        </td>
    </tr>
</table>

I sometimes use:

<div style="width:100%; text-align:center">content</div>

But this doesn't seem quite right. I'm not trying to align text, I'm trying to align content. Also, this seems to have an effect on the text alignment of enclosed elements, which requires tweaking to fix. One thing I don't get is: why isn't there a float:center style? It seems like that would be the best solution. Hopefully, I'm missing something and there is a perfect CSS way to do this.

like image 960
Paul Keister Avatar asked Apr 06 '09 18:04

Paul Keister


People also ask

How do I center my content in CSS?

To just center the text inside an element, use text-align: center; This text is centered.

How do I center my web content?

How To Center Your Website. Use a container element and set a specific max-width . A common width many websites use is 960px. To actually center the page, add margin: auto .

How do I center align table contents?

We use the CSS property text-align, to center align text in table cells. We use inline, internal style sheet for text alignment in table cells. The text-align property of CSS sets the alignment of the content in <th> and <td>. By default, the content of <th> are center-aligned and the content of <td> are left-aligned.


1 Answers

You are right that text-align is intended for aligning text. It's actually only Internet Explorer that lets you center anything other than text with it. Any other browser handles this correctly and doesn't let block elements be affected by text-align.

To center block elements using css you use margin: 0 auto; just as Joe Philllips suggested. Although you don't need to keep the table at all.

The reason that there is no float: center; is that floating is intended to place elements (typically images) either to the left or the right and have text flow around them. Floating something in the center doesn't make sense in this context as that would mean that the text would have to flow on both sides of the element.

like image 92
Guffa Avatar answered Sep 30 '22 20:09

Guffa