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.
To just center the text inside an element, use text-align: center; This text is centered.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With