为 html table 中所有类似的 tds 设置样式参数

Setting the style parameters for all similar tds in html table

我正在尝试为 html table 中的所有 tds 设置相似的样式,如下所示:

<table>
<tbody>
<tr>
<td style="text-align: right; direction: ltr;">1</td>
<td style="text-align: right; direction: ltr;">2</td>
<td style="text-align: right; direction: ltr;">3</td>
.
.
.
</tr>
</tbody>
</table>

有没有一种方法可以将所有这些 tds 中的文本定义为右对齐并指向左侧,而无需为每个单元格重复相同的内容?我知道我可以通过某种方式定义 Id 或 class 在 css 文件中执行此操作,但是有没有办法在同一个 html 文件中执行此操作?

以下 css 将对您页面上所有 table 的所有单元格应用文本对齐。如果您希望每个 table 单独显示,请设置 table 一个 ID 或 Class 并对其应用以下代码:

table td{
    text-align: right;
}

要将其包含在同一个 html 文件中,只需将其添加到 html:

头部部分的样式块中

<html>

<head>
  <style type="text/css">
    .MyTable td {
      width:100px;
      border:1px solid purple;
      text-align: right !important; /*this attribute will be forced*/
      direction: ltr;
    }
  </style>

</head>

<body>
  <table class="MyTable">
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
      </tr>
    </tbody>
  </table>
</body>

</html>

您可以将 class="right" 添加到 <td> 元素,然后定义以下 CSS class:

.right {
    text-align: right;
}

您可以重命名 class and/or 添加任何其他属性(如 direction 等)。

如果您希望在 HTML 代码中不添加任何额外标记,您可以创建以下 CSS class:

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

这会将 table 中的第 2 列右对齐。如果您想更改列号,只需更改寄生虫中的数字即可。