阅读(1882)

HTML 表列

最后一次修改 2017年08月03日

HTML表列

colgroup  - 表列组

HTML表是面向行的。将单元格的定义放在 tr 中元素中,并逐行构建表。

要将样式应用于列,我们可以使用 colgroup col 元素。

具有局部属性 span colgroup 元素表示一组列。

colgroup 元素可以包含零个或多个 col 元素。

width,char,charoff valign 属性已过时。

以下代码显示了 colgroup 元素的使用。

<!DOCTYPE HTML><html><head><style>#colgroup1 {
  background-color: red
}#colgroup2 {  background-color: green;  font-size: small
}</style></head><body>
  <table>
    <colgroup id="colgroup1" span="3" />
    <colgroup id="colgroup2" span="2" />
    <thead>
      <tr>
        <th>Rank</th>
        <th>Name</th>
        <th>Color</th>
        <th colspan="2">Size & Votes</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th>Favorite:</th>
        <td>XML</td>
        <td>HTML</td>
        <td>CSS</td>
        <td>500</td>
      </tr>
      <tr>
        <th>2nd Favorite:</th>
        <td>CSS</td>
        <td>Java</td>
        <td>Javascript</td>
        <td>450</td>
      </tr>
    </tbody>
  </table></body></html>

上面的代码定义了两个 colgroup 元素。 span 属性指定 colgroup 元素应用于多少列。

列表中的第一个 colgroup 应用于表中的前三列,其他元素应用于后两列。

全局 id 属性是为每个 colgroup 元素定义的,CSS样式通过使用 id 值作为选择器来定义。


col  - 表单个列

您可以使用 col 元素而不是 colgroup 元素的 span 属性定义组。

col 元素具有局部属性: span

align,width,char,charoff valign 属性已过时。

您可以将样式应用于列的组和该组中的单个列。 col 元素放置在 colgroup 元素内部, col 的每个实例表示组中的一列。

以下代码使用 col 元素。

<!DOCTYPE HTML>
<html>
<head>
<style>
#colgroup1 {
  background-color: red
}

#col3 {
  background-color: green;
  font-size: small
}
</style>
</head>
<body>
  <table>
    <colgroup id="colgroup1">
      <col id="col1And2" span="2" />
      <col id="col3" />
    </colgroup>
    <colgroup id="colgroup2" span="2" />
    <thead>
      <tr>
        <th>Rank</th>
        <th>Name</th>
        <th>Color</th>
        <th colspan="2">Size & Votes</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th>Favorite:</th>
        <td>1234</td>
        <td>1234</td>
        <td>1234</td>
        <td>500</td>
      </tr>
      <tr>
        <th>2nd Favorite:</th>
        <td>1234</td>
        <td>1234</td>
        <td>1234</td>
        <td>450</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

您可以使用 span 属性创建表示 colgroup 中两列的col 元素。

如果不使用 span 属性,col 元素表示单个列。

上面的代码将样式应用于 colgroup 和其它包含的 col 元素之一。