【问题标题】:Row header in separate row单独行中的行标题
【发布时间】:2023-11-01 00:41:01
【问题描述】:

我知道这是语义上有效的 HTML(已在 W3C 验证),但问题是它是否合乎逻辑?带有名称的 th 是否作为标题应用于下一行中的单元格?

<table>
    <thead>
        <tr>
            <th>Country</th>
            <th>Age</th>
            <th>Sex</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th colspan="3">John Baker</th>
        </tr>
        <tr>
            <td>US</td>
            <td>27</td>
            <td>Male</td>
        </tr>
    </tbody>
</table>

我想要的效果是将名称作为其余数据的标题,并将其放在表中的单独行上。

或者我应该将它们保持在同一行并使用 CSS 将 th 移动到单独的行?

【问题讨论】:

  • 看起来像您期望的那样吗? &lt;th&gt; 本质上只不过是粗体 &lt;td&gt;
  • 我看起来确实像我预期的那样。明智的造型只不过是一个大胆的 td,但我希望语义正确。支持屏幕阅读器等功能。
  • 语义上没有意义。 th 用于列的标题,您放入其中的内容实际上是行的属性。
  • @StephanMuller 你是对的,它是财产。我在 thead 中添加了一个新的隐藏 th,并在行中使用了 td。

标签: html html-table semantics semantic-markup


【解决方案1】:

如果您的&lt;th&gt; 特定于&lt;tbody&gt;(请记住,每个&lt;table&gt; 可以有多个&lt;tbody&gt;s),那么语义上正确的做法是给它一个scope attribute

<th colspan="3" scope="rowgroup">John Baker</th>

或者,如果您想将特定单元格定义为以特定&lt;th&gt; 为首,那么您可以使用headers attribute

<table>
    <thead>
        <tr>
            <th id="header-country">Country</th>
            <th id="header-age">Age</th>
            <th id="header-sex">Sex</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th colspan="3" id="header-1">John Baker</th>
        </tr>
        <tr>
            <td headers="header-country header-1">US</td>
            <td headers="header-age header-1">27</td>
            <td headers="header-sex header-1">Male</td>
        </tr>
    </tbody>
</table>

【讨论】:

    最近更新 更多