HTML 表格的高级功能和辅助功能

在本模块的第二篇文章中,我们将介绍 HTML 表格的一些更高级的功能,例如标题/摘要以及将行分组为表头、正文和页脚部分,以及查看针对视障用户的表格的可访问性 。

¥In the second article in this module, we look at some more advanced features of HTML tables — such as captions/summaries and grouping your rows into table head, body and footer sections — as well as looking at the accessibility of tables for visually impaired users.

先决条件: HTML 基础知识(参见 HTML 简介)。
目标: 了解更高级的 HTML 表格功能以及表格的可访问性。

使用 <caption> 添加标题到表格

¥Adding a caption to your table with <caption>

你可以通过将表格放在 <caption> 元素内并将其嵌套在 <table> 元素内来为表格提供标题。你应该将其放在起始 <table> 标签的正下方。

¥You can give your table a caption by putting it inside a <caption> element and nesting that inside the <table> element. You should put it just below the opening <table> tag.

html

<table>
  <caption>
    Dinosaurs in the Jurassic period
  </caption></table>


正如你可以从上面的简短示例中推断出的那样,标题旨在包含表格内容的描述。这对于所有希望在浏览页面时快速了解该表格是否对他们有用的读者来说非常有用,特别是对于盲人用户。用户可以依靠标题,然后决定是否更详细地阅读表格,而不是让屏幕阅读器读出许多单元格的内容来了解表格的内容。

¥As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screen reader read out the contents of many cells just to find out what the table is about, the user can rely on a caption and then decide whether or not to read the table in greater detail.

标题直接放置在 <table> 标签下方。

¥A caption is placed directly beneath the <table> tag.

注意:summary 属性也可以用在 <table> 元素上来提供描述 - 这也可以由屏幕阅读器读出。但是,我们建议改用 <caption> 元素,因为 summary 已被弃用,并且视力正常的用户无法阅读(它不会出现在页面上)。

¥Note: The summary attribute can also be used on the <table> element to provide a description — this is also read out by screen readers. We'd recommend using the <caption> element instead, however, as summary is deprecated and can't be read by sighted users (it doesn't appear on the page).

主动学习:添加标题

¥Active learning: Adding a caption

让我们尝试一下,回顾一下我们在上一篇文章中第一次遇到的示例。

¥Let's try this out, revisiting an example we first met in the previous article.

  1. 打开你的语言老师从 HTML 表格基础知识 年底开始的学校时间表,或制作我们的 timetable-fixed.html 文件的本地副本。
  2. 为表格添加合适的标题。
  3. 保存代码并在浏览器中打开它以查看其外观。

注意:你可以在 GitHub 上找到我们的版本 - 请参阅 timetable-caption.html (也看到它直播)。

¥Note: You can find our version on GitHub — see timetable-caption.html (see it live also).

使用 <thead>、 <tbody> 和 <tfoot> 添加结构

¥Adding structure with <thead>, <tbody>, and <tfoot>

当表的结构变得更加复杂时,为它们提供更多的结构定义会很有用。一种明确的方法是使用 <thead><tbody><tfoot>,它们允许你标记表格的页眉、正文和页脚部分。

¥As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using <thead>, <tbody>, and <tfoot>, which allow you to mark up a header, body, and footer section for the table.

这些元素不会使屏幕阅读器用户更容易访问表格,并且它们本身不会产生任何视觉增强。然而,它们对于样式和布局非常有用 - 充当将 CSS 添加到表格的有用钩子。举一些有趣的例子,如果表格很长,你可以使表格页眉和页脚在每个打印页面上重复,并且可以使表格主体显示在单个页面上,并通过向上和向下滚动来显示内容 。

¥These elements don't make the table any more accessible to screen reader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout — acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

要使用它们,应按以下顺序包含它们:

¥To use them, they should be included in the following order:

  • <thead> 元素必须包含表的标题部分 - 这通常是包含列标题的第一行,但情况不一定总是如此。如果你使用 <col>/<colgroup> 元素,则表标题应位于这些元素的正下方。
  • <tbody> 元素需要封装表格内容的主要部分,而不是表格页眉或页脚。
  • <tfoot> 元素需要封装表的页脚部分 - 例如,这可能是最后一行,其中前一行中的项目相加。

注意:<tbody> 始终包含在每个表中,如果你未在代码中指定它,则隐式包含它。要检查这一点,请打开之前不包含 <tbody> 的示例之一,然后查看 浏览器开发者工具 中的 HTML 代码 - 你将看到浏览器已为你添加了此标记。你可能想知道为什么你应该费心包含它 - 你应该这样做,因为它可以让你更好地控制表格结构和样式。

¥Note: <tbody> is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include <tbody> and look at the HTML code in your browser developer tools — you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling.

主动学习:添加表结构

¥Active learning: Adding table structure

让我们将这些新元素付诸行动。

¥Let's put these new elements into action.

  1. 首先,在新文件夹中制作 spending-record.htmlminimal-table.css 的本地副本。
  2. 尝试在浏览器中打开它 - 你会发现它看起来不错,但它还有待改进。包含支出金额总和的 "SUM" 行似乎位于错误的位置,并且代码中缺少一些详细信息。
  3. 将明显的标题行放入 <thead> 元素内,将 "SUM" 行放入 <tfoot> 元素内,将其余内容放入 <tbody> 元素内。
  4. 保存并刷新,你将看到添加 <tfoot> 元素导致 "SUM" 行下降到表格底部。
  5. 接下来,添加 colspan 属性以使 "SUM" 单元格跨越前四列,因此实际数字显示在 "成本" 列的底部。
  6. 让我们向表格中添加一些简单的额外样式,让你了解这些元素对于应用 CSS 有多有用。在 HTML 文档的头部,你将看到一个空的 <style> 元素。在此元素内,添加以下 CSS 代码行:
    css
    tbody {
      font-size: 95%;
      font-style: italic;
    }
    
    tfoot {
      font-weight: bold;
    }
    
  7. 保存并刷新,看看结果。如果 <tbody><tfoot> 元素没有到位,你就必须编写更复杂的选择器/规则才能应用相同的样式。

注意:我们不期望你现在就完全理解 CSS。当你浏览我们的 CSS 模块时,你将了解更多相关内容(CSS 简介 是一个很好的起点;我们还有一篇专门关于 样式表 的文章)。

¥Note: We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules (Introduction to CSS is a good place to start; we also have an article specifically on styling tables).

你完成的表格应如下所示:

¥Your finished table should look something like the following:

注意:你还可以在 GitHub 上找到它,名称为 spending-record-finished.html

¥Note: You can also find it on GitHub as spending-record-finished.html.

嵌套表

¥Nesting Tables

只要包含完整的结构(包括 <table> 元素),就可以将一个表嵌套在另一个表中。通常不建议这样做,因为它会使标记更加混乱,并且屏幕阅读器用户更难访问,并且在许多情况下,你可能只是将额外的单元格/行/列插入到现有表中。但有时这是必要的,例如,如果你想轻松地从其他来源导入内容。

¥It is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screen reader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.

以下标记显示了一个简单的嵌套表:

¥The following markup shows a simple nested table:

html

<table id="table1">
  <tr>
    <th>title1</th>
    <th>title2</th> 
    <th>title3</th>
  </tr>
  <tr>
    <td id="nested">
      <table id="table2">
        <tr>
          <td>cell1</td>
          <td>cell2</td> 
          <td>cell3</td>
        </tr>
      </table>


    </td>
    <td>cell2</td>
    <td>cell3</td>
  </tr>
  <tr>
    <td>cell4</td>
    <td>cell5</td>
    <td>cell6</td>
  </tr>
</table>

其输出看起来像这样:

¥The output of which looks something like this:

css
table {
  border-collapse: collapse;
}
td,
th {
  border: 1px solid black;
  padding: 10px 20px;
}

供视障用户使用的表格

¥Tables for visually impaired users

让我们简要回顾一下如何使用数据表。表格是一个方便的工具,可以让我们快速访问数据并查找不同的值。例如,只需浏览下表即可了解 2016 年 8 月期间根特售出了多少枚戒指。为了理解其信息,我们在此表中的数据与其列和/或行标题之间建立视觉关联。

¥Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, it takes only a short glance at the table below to find out how many rings were sold in Gent during August 2016. To understand its information we make visual associations between the data in this table and its column and/or row headers.

Items Sold August 2016
衣服 访问器
裤子 裙子 连衣裙 手链 戒指
比利时 安特卫普 56 22 43 72 23
根特 46 18 50 61 15
布鲁塞尔 51 27 38 69 28
荷兰人 阿姆斯特丹 89 34 69 85 38
乌得勒支 80 12 43 36 19

但如果你无法建立这些视觉关联怎么办?那么如何才能读懂上面这样的表格呢?视障人士经常使用屏幕阅读器向他们朗读网页上的信息。当你阅读纯文本时这没有问题,但解释表格对于盲人来说可能是一个很大的挑战。然而,通过适当的标记,我们可以用程序化的关联来代替视觉关联。

¥But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screen reader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.

注意:根据 2017 年世界卫生组织数据,约有 2.53 亿人患有视力障碍。

¥Note: There are around 253 Million people living with Visual Impairment according to WHO data in 2017.

本文的这一部分提供了使表格尽可能易于访问的进一步技术。

¥This section of the article provides further techniques for making tables as accessible as possible.

使用列标题和行标题

¥Using column and row headers

屏幕阅读器将识别所有标题并使用它们在这些标题和它们相关的单元格之间建立编程关联。列标题和行标题的组合将识别和解释每个单元格中的数据,以便屏幕阅读器用户可以像视力正常的用户一样解释表格。

¥Screen readers will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screen reader users can interpret the table similarly to how a sighted user does.

我们已经在上一篇文章中介绍了标题 - 请参阅 使用 <th> 元素添加标头

¥We already covered headers in our previous article — see Adding headers with <th> elements.

范围属性

¥The scope attribute

本文的一个新主题是 scope 属性,可以将其添加到 <th> 元素中,以准确告诉屏幕阅读器该标题是哪些单元格的标题 - 例如,它是所在行的标题还是列的标题 ?回顾之前的支出记录示例,你可以明确地将列标题定义为如下所示的列标题:

¥A new topic for this article is the scope attribute, which can be added to the <th> element to tell screen readers exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:

html
<thead>
  <tr>
    <th scope="col">Purchase</th>
    <th scope="col">Location</th>
    <th scope="col">Date</th>
    <th scope="col">Evaluation</th>
    <th scope="col">Cost (€)</th>
  </tr>
</thead>

每行都可以有一个像这样定义的标题(如果我们添加行标题和列标题):

¥And each row could have a header defined like this (if we added row headers as well as column headers):

html
<tr>
  <th scope="row">Haircut</th>
  <td>Hairdresser</td>
  <td>12/09</td>
  <td>Great idea</td>
  <td>30</td>
</tr>

例如,屏幕阅读器将识别这样结构的标记,并允许用户立即读出整个列或行。

¥Screen readers will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.

scope 还有两个可能的值 — colgrouprowgroup。这些用于位于多列或多行顶部的标题。如果你回顾一下本文本节开头的 "2016 年 8 月售出的商品" 表,你会发现 "衣服" 单元格位于 "裤子"、"裙子" 和 "连衣裙" 单元格上方。所有这些单元格都应标记为标题 (<th>),但 "衣服" 是位于顶部并定义其他三个子标题的标题。因此,"衣服" 应该获得 scope="colgroup" 的属性,而其他人将获得 scope="col" 的属性:

¥scope has two more possible values — colgroup and rowgroup. These are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items Sold August 2016" table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers (<th>), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of scope="colgroup", whereas the others would get an attribute of scope="col":

html
<thead>
  <tr>
    <th colspan="3" scope="colgroup">Clothes</th>
  </tr>
  <tr>
    <th scope="col">Trousers</th>
    <th scope="col">Skirts</th>
    <th scope="col">Dresses</th>
  </tr>
</thead>

这同样适用于多个分组行的标题。再看一下 "2016 年 8 月售出的商品" 表,这次重点关注具有 "阿姆斯特丹" 和 "乌得勒支" 标题 (<th>) 的行。你会注意到,"荷兰人" 标题也标记为 <th> 元素,跨越两行,是其他两个子标题的标题。因此,应在此标题单元格上指定 scope="rowgroup",以帮助屏幕阅读器创建正确的关联:

¥The same applies to headers for multiple grouped rows. Take another look at the "Items Sold August 2016" table, this time focusing on the rows with the "Amsterdam" and "Utrecht" headers (<th>). You'll notice that the "The Netherlands" header, also marked up as a <th> element, spans both rows, being the heading for the other two subheadings. Therefore, scope="rowgroup" should be specified on this header cell to help screen readers create the correct associations:

html
<tr>
  <th rowspan="2" scope="rowgroup">The Netherlands</th>
  <th scope="row">Amsterdam</th>
  <td>89</td>
  <td>34</td>
  <td>69</td>
</tr>
<tr>
  <th scope="row">Utrecht</th>
  <td>80</td>
  <td>12</td>
  <td>43</td>
</tr>

id 和 headers 属性

¥The id and headers attributes

使用 scope 属性的替代方法是使用 idheaders 属性在标头和单元格之间创建关联。

¥An alternative to using the scope attribute is to use id and headers attributes to create associations between headers and cells.

headers 属性采用无序、以空格分隔的 strings 列表,每个 <th> 元素对应于为数据单元格(<td> 元素)或另一个标题单元格(<th> 元素)提供标题的唯一 id

¥The headers attribute takes a list of unordered, space-separated strings, each corresponding to the unique id of the <th> elements that provide headings for either a data cell (<td> element) or another header cell (<th> element).

这为你的 HTML 表格提供了表格中每个单元格位置的明确定义,由其所属的每列和行的标题定义,有点像电子表格。为了使其正常工作,表格确实需要列标题和行标题。

¥This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.

回到我们的 "2016 年 8 月售出的商品" 示例,我们可以使用 idheaders 属性,如下所示:

¥Returning to our "Items Sold August 2016" example, we can use the id and headers attributes as follows:

  1. 向表中的每个 <th> 元素添加唯一的 id
  2. headers 属性添加到充当副标题的每个 <th> 元素,即其上方有一个标题元素。该值是位于顶部并定义副标题的标题的 id,在我们的示例中,列标题为 "clothes",行标题为 "belgium"
  3. headers 属性添加到每个 <td> 元素,并以空格分隔列表的形式添加关联的 <th> 元素的 id。你可以像在电子表格中一样继续操作:找到数据单元格并搜索行和列的相应标题。指定的 id 的顺序并不重要,但你应该保持一致以保持有序。
html
<thead>
  <tr>
    <th id="clothes" colspan="3">Clothes</th>
  </tr>
  <tr>
    <th id="trousers" headers="clothes">Trousers</th>
    <th id="skirts" headers="clothes">Skirts</th>
    <th id="dresses" headers="clothes">Dresses</th>
  </tr>
</thead>
<tbody>
  <tr>
    <th id="belgium" rowspan="3">Belgium</th>
    <th id="antwerp" headers="belgium">Antwerp</th>
    <td headers="antwerp belgium clothes trousers">56</td>
    <td headers="antwerp belgium clothes skirts">22</td>
    <td headers="antwerp belgium clothes dresses">43</td>
  </tr>
</tbody>

注意:此方法在标题和数据单元格之间创建非常精确的关联,但它使用更多标记,并且不会留下任何错误空间。scope 方法通常足以满足大多数表的需要。

¥Note: This method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors. The scope approach is usually sufficient for most tables.

主动学习:使用范围和标题

¥Active learning: playing with scope and headers

  1. 对于最后一个练习,我们希望你首先在新目录中制作 items-sold.htmlminimal-table.css 的本地副本。
  2. 现在尝试添加适当的 scope 属性以使该表更易于访问。
  3. 最后,尝试制作起始文件的另一个副本,这次通过使用 idheaders 属性创建精确且显式的关联来使表更易于访问。

注意:你可以根据我们完成的示例检查你的工作 - 请参阅 items-sold-scope.html (也看到这个直播) 和 items-sold-headers.html (也看到这个直播)。

¥Note: You can check your work against our finished examples — see items-sold-scope.html (also see this live) and items-sold-headers.html (see this live too).

概括

¥Summary

关于 HTML 中的表格,你还可以了解一些其他内容,但这就是你现在需要了解的全部内容。接下来,你可以用我们的 HTML 表格评估 来测试一下自己。玩得开心!

¥There are a few other things you could learn about tables in HTML, but this is all you need to know for now. Next, you can test yourself with our HTML tables assessment. Have fun!

如果你已经在学习 CSS 并且在评估中取得了良好的成绩,你可以继续学习 HTML 表格样式 - 请参阅 样式表

¥If you are already learning CSS and have done well on the assessment, you can move on and learn about styling HTML tables — see Styling tables.

如果你想开始学习 CSS,请查看 CSS 学习区

¥If you want to get started with learning CSS, check out the CSS Learning Area!