Better way to right align text in HTML Table

You could use the nth-child pseudo-selector. For example:

table.align-right-3rd-column td:nth-child(3)
{
  text-align: right;
}

Then in your table do:

<table class="align-right-3rd-column">
  <tr>
    <td></td><td></td><td></td>
    ...
  </tr>
</table>

Edit:

Unfortunately, this only works in Firefox 3.5. However, if your table only has 3 columns, you could use the sibling selector, which has much better browser support. Here's what the style sheet would look like:

table.align-right-3rd-column td + td + td
{
  text-align: right;
}

This will match any column preceded by two other columns.


Updated (after 10+ years!): Yes! It's possible to do this more efficiently now, with widespread practical browser support, using the nth-child selector.

HTML:

<table>
<tr>
<td>foo 1</td>
<td>bar 1</td>
<td>baz 1</td>
<td>bap 1</td>
</tr>
<tr>
<td>foo 2</td>
<td>bar 2</td>
<td>baz 2</td>
<td>bap 2</td>
</tr>
</table>

CSS:

table td { width: 20em; border: 1px solid black; }
table td:nth-child(3) { text-align: end; }

https://jsfiddle.net/mv83qszL/

Previously, it was not possible to do this, because browser support used to be inconsistent and hit-or-miss, especially with regard to newer CSS features. This made it impossible to use more elegant, efficient solutions -- and required lots of repetitive markup and class definitions in order to get consistent results across the audience's browser space.

See the edit history for the previous version of this answer.

Tags:

Html

Css