What is the correct CSS way to implement right-justified text in table columns?

To my surprise, I just found out that applying text alignment to a table column is rather poorly supported in current browsers. Neither Firefox 3.5.2, Safari 4.0.3, nor IE8 show the "amount" column below right-aligned.

HTML:

<table class="full_width">
  <caption>Listing employees of department X</caption>
  <col></col>
  <col></col>
  <col></col>
  <col class="amount" width="180"></col>
  <thead>
    <tr>
      <th>Name</th>
      <th>Phone number</th>
      <th>Email</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>+45 2373 6220</td>
      <td>john@doe.com</td>
      <td>20000</td>
    </tr>
  </tbody>
</table>

      

CSS

.amount{
  text-align: right;
}

      

Why doesn't it work? Also I tried (via firebug) disabling Firefox's own rule that aligns TD elements, but that didn't work either.

I see that the rule of setting the background color in the amount of css class actually works. Therefore, I know that the .amount class applies to all columns:

CSS

.amount{
  text-align: right;
  background-color: aqua;
}

      

The CSS 2 spec seems to say that only four attributes are supported by the col element - see Why are stylesheet columns not allowed?

Best Solution Criteria: Enough cross-browser support needed (not necessarily in IE6, where I could live using jquery or conditional comment to enable a specific solution). Also, I expect to apply multiple classes to multiple different columns (i.e. class="amount before_tax"

)

I would not like to set classes on the corresponding td on each line. What are my options?

+2


source to share


5 answers


I would not like to set the classes to the corresponding td on every line. What are my options?



It would be like this: class on every td.

+7


source


If you don't want to add a class to every cell in the column manually, your only option is to use javascript to do this.

With jQuery:



$("table tbody tr td:eq(3)").addClass("amount");

      

+2


source


You can always set the class on the last element on the line:

.full_width td:last-child {
    text-align: right;
}

      

+1


source


you need to set the class on td elements. I think that's the only way.

0


source


Your answers got me thinking about creating a JQuery script that parses COL elements. Then it has to find each line that matches the corresponding COL and apply the COL class to each element like this:

enter code here

$ ("table tbody tr td: eq (3)"). addClass ("amount");

But only do this (as a performance improvement) if the class definition contains the text-align in it.

Of course, a fully integrated implementation of colspan and COLGROUP would be overkill and most likely not supported.

Any thoughts on this idea?

0


source







All Articles