Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text in table cell

I can't seem to find the answer to my issue. I have a table with two rows and two columns (like the code shown below), how do I center align the text in specific cells. I would like to center align the text in one or two of the cells - not all the cells.

<div style="text-align: center;">     <table style="margin: 0px auto;" border="0">         <tbody>             <tr>                 <td>Cell 1</td>                 <td>Cell 2</td>             </tr>             <tr>                 <td>Cell 3</td>                 <td>Cell 4</td>             </tr>         </tbody>     </table> </div> 
like image 251
Jack Stevens Avatar asked Oct 03 '11 21:10

Jack Stevens


People also ask

How do I center text vertically in a table?

1 Select the text you want to center between the top and bottom margins. 2 On the Page Layout tab, click the Page Setup Dialog Box Launcher. 3 Select the Layout tab. 4 In the Vertical alignment box, click Center 5 In the Apply to box, click Selected text, and then click OK.

How do you center data in a table?

To center this table, you would need to add ;margin-left:auto;margin-right:auto; to the end of the style attribute in the <table> tag. The table tag would look like the following. Changing the style attribute in the <table> tag, as shown above, results in the table being centered on the web page, as shown below.


1 Answers

I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:

.ui-helper-center {     text-align: center; } 

And then add the ui-helper-center class to the table cells for which you wish to control the alignment:

<td class="ui-helper-center">Content</td> 

EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.

See Gabe's answer for how to include the CSS rule into your page.

like image 188
Cᴏʀʏ Avatar answered Oct 04 '22 20:10

Cᴏʀʏ