我如何构造一个表头而不是跨越 HTML 中的多行



我想构造一个表如下:

|   Major Heading 1    |  Major Heading 2    |
|   Minor1  |  Minor2  | Minor3  |  Minor4   |
----------------------------------------------
|   col1    |   col2   |   col3  |    col4   |
rest of table ...

看到 TH 元素只有 1 行,我如何构建标题行,例如列排列?分层表似乎不是一个好的选择,因为列宽不会对齐,而且我也不能将带有 TH 标签的两行与 colspan 一起使用。

这就是

我的做法(在 http://jsfiddle.net/7pDqb/工作小提琴)在Chrome中进行测试。

th, td { border: 1px solid black }
<table>
  <thead>
    <tr>
      <th colspan="2">Major 1</th>
      <th colspan="2">Major 2</th>
    </tr>
    <tr>
      <th>col1</th>
      <th>col2</th>
      <th>col3</th>
      <th>col4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>data1</td>
      <td>data2</td>
      <td>data3</td>
      <td>data4</td>
    </tr>
  </tbody>
</table>

您是否不小心使用了rowspan而不是colspan?还是您不小心忘记了结束</tr>标签?

根据tvanfosson的答案,我将在th元素上使用scope属性,以实现语义和可访问性目的:

th, td { border: 1px solid black }
<table>
  <thead>
    <tr>
      <th colspan="2" scope='colgroup'>Major Heading 1</th>
      <th colspan="2" scope='colgroup'>Major Heading 2</th>
    </tr>
    <tr>
      <th scope='col'>Minor1</th>
      <th scope='col'>Minor2</th>
      <th scope='col'>Minor3</th>
      <th scope='col'>Minor4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col1</td>
      <td>col2</td>
      <td>col3</td>
      <td>col4</td>
    </tr>
  </tbody>
</table>

但是,除了标题单元格跨越多列的情况外,标题单元格跨越两行的表也经常出现。

下面是一个示例。请参阅下面的col 5data5

    <table>
        <thead>
            <tr>
                <th colspan="2">Major 1</th>
                <th colspan="2">Major 2</th>
                <th rowspan="2">col 5</th>
            </tr>
            <tr>
                <th>col1</th>
                <th>col2</th>
                <th>col3</th>
                <th>col4</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>data1</td>
                <td>data2</td>
                <td>data3</td>
                <td>data4</td>
                <td>data5</td>
            </tr>
        </tbody>
    </table>

这是小提琴。

W3C的Web可访问性倡议(WAI)网站表示使用如下所示的标记结构。

(请注意,网站上示例表中呈现的标记与示例标记中显示的标记略有不同。请参阅链接并检查示例表。

来源: https://www.w3.org/WAI/tutorials/tables/irregular/#table-with-two-tier-headers

<table>
  <col>
  <colgroup span="2"></colgroup>
  <colgroup span="2"></colgroup>
  <tr>
    <td rowspan="2"></td>
    <th colspan="2" scope="colgroup">Mars</th>
    <th colspan="2" scope="colgroup">Venus</th>
  </tr>
  <tr>
    <th scope="col">Produced</th>
    <th scope="col">Sold</th>
    <th scope="col">Produced</th>
    <th scope="col">Sold</th>
  </tr>
  <tr>
    <th scope="row">Teddy Bears</th>
    <td>50,000</td>
    <td>30,000</td>
    <td>100,000</td>
    <td>80,000</td>
  </tr>
  <tr>
    <th scope="row">Board Games</th>
    <td>10,000</td>
    <td>5,000</td>
    <td>12,000</td>
    <td>9,000</td>
  </tr>
</table>