0

I have a report that's displayed in a table, the text inside tds must be centered but left justified, how can I accomplish that ?

<td style="text-align: center;"><?=$row['column']?></td>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Digital fortress
  • 737
  • 8
  • 18
  • 31

2 Answers2

0

If you're unable to modify the mark-up, the only option I can suggest is to use padding:

 td {
    width: 7em;
    padding: 0 1em;
    border: 1px solid #000;
 }

JS Fiddle demo.

This will place the text 1em away from the left and right boundaries of the cell, but retain left-justification within those boundaries.

Remember that padding will be added to the width of the cell, though, so with the above the dimensions of the cell will be width + padding-left + padding-right + border-left + border-right, so: (7em + 1em + 1em + 1px + 1px). To contain the padding and borders within the defined width you can use box-sizing in compliant browsers:

 td {
    width: 7em;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -o-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding: 0 1em;
    border: 1px solid #000;
 }

JS Fiddle demo.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • This is a good way of achieving it, but if the table width is 100%, and it expands with screen resolution, the text wont be centered inside tables, right ? – Digital fortress Feb 03 '13 at 13:11
  • I dont know the table width, it's set to 100%, so everytime the screen size changes, table width would change, I need to make sure its always centered – Digital fortress Feb 03 '13 at 13:20
  • This will be centered within the cell. If there are constraints on your table, or the cells, please add that to the question. And explain clearly, show images if they'll help. As it is, I don't understand what you're asking in your comment: the size of the `table` has nothing to do with the centering of the text in the `td`. It might not be legible if the cells are too small, but the browser will still do its best to position it appropriately within the constraints of the CSS. – David Thomas Feb 03 '13 at 13:25
0

You can contain the text in a div and center it in the td like this:

HTML

<td><div class="inner">left justified text in a centered block</div></td>

CSS

.inner {
    width: 20%;
    display: table;
    margin: 0 auto;
}

JSFiddle Demo

You don't have to specify align=left in the div. It is aligned left by default.

Antony
  • 14,900
  • 10
  • 46
  • 74