Shelvacu
Shelvacu

Reputation: 4362

How to make <table> column right-aligned

<table>
  <colgroup>
    <col>
    <col style='text-align:right'>
  </colgroup>
  <tbody>
    <tr>
      <td>Sample text</td>
      <td>This text should be right-aligned</td>
    </tr>
    <tr>
      <td></td>
      <td>
        <div id='spacer' style='width:100px'>
          I'm a spacer
        </div>
      </td>
    </tr>
  </tbody>
</table>

Results in text that isn't right aligned. If the same style is applied to the td element it works fine. How do I right-align text in a column without having to apply a style to every td element?

Upvotes: 0

Views: 772

Answers (2)

kzhao14
kzhao14

Reputation: 2630

Add the following CSS:

table.tableClass tr td:nth-child(2) {
   text-align: right;
}

the number after nth-child( is the column, so for this case it would be 2 because it's the second column. Fiddle: http://jsfiddle.net/p97vdo2p/1/

Upvotes: 2

Andrew
Andrew

Reputation: 1324

HTML isn't rendered by column, it's rendered by rows. That's why there <tr></tr> (table rows) exist, but <tc></tc> (table columns) do not. That being said, the easiest way to style a column in HTML, is by applying the same CSS class to every <td></td> in the given column. You can type in the same class to every one manually, or you could write it programmatically, via javascript or a server-side script.

Upvotes: 1

Related Questions