2

To my surprise I just found out that applying text-alignment to a table column is fairly bad supported in current browsers. Neither Firefox 3.5.2, Safari 4.0.3 or IE8 shows the "amount" column below as 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 isn't this working? Also I tried (via firebug) to turn off Firefox' native rule that left-aligns TD elements, but that didn't work either.

I can see that setting background color rule in the amount css class actually works. So I know that the .amount class is applied to all columns:

CSS

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

The CSS 2 spec apparently says that only four attributes are supported by col element -- see Why is styling table columns not allowed?

Criteria for selecting the best solution: must be supported fairly cross-browser (not necessarily in IE6 where I could live with using jquery or a conditional comment to include a specific solution). Also, I expect to apply multiple classes multiple different columns (ie. class="amount before_tax")

I'd hate to set classes on the relevant td in each row. What are my options?

4

5 回答 5

7

我不想在每一行的相关 td 上设置类。我有哪些选择?

就是这样:每个 td.

于 2009-09-08T08:25:59.467 回答
2

如果您不想手动将类添加到列中的每个单元格,则唯一的其他选择是使用 javascript 来完成。

使用 jQuery:

$("table tbody tr td:eq(3)").addClass("amount");
于 2009-09-08T08:29:01.847 回答
1

您始终可以在一行中的最后一个元素上设置一个类:

.full_width td:last-child {
    text-align: right;
}
于 2009-09-08T08:52:54.623 回答
0

您必须在 td 元素上设置类。我认为这是唯一的方法。

于 2009-09-08T08:28:20.140 回答
0

您的回答让我考虑创建一个解析 COL 元素的 JQuery 脚本。然后它应该找到与相应 COL 匹配的每一行,并将 COL 类应用于每个元素,如下所示:

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

但只有在类定义中包含 text-align 时才这样做(作为性能改进)。

当然,一个完整的 colspan 和 COLGROUP 元素的复杂实现将是多余的,很可能不受支持。

对这个想法有什么想法吗?

于 2009-09-09T11:08:54.973 回答