如果表格有表格主体,表格行 (
<tr>
) 是否必须位于表格主体 (<tbody>
) 中,还是可以存在于表格主体之外?
<table>
<tr>
<td colspan='2'>...</td>
</tr>
<tbody>
<tr>
<td>...</td>
<td>...</td>
</tr>
</tbody>
<tr>
<td colspan='2'>...</td>
</tr>
<tbody>
<tr>
<td>...</td>
<td>...</td>
</tr>
</tbody>
</table>
不,
<tr>
可以位于 <thead>
、<tbody>
、<tfoot>
中,也可以不必位于其中任何一个中。
与 Terrill Thomson 所说的相反,在
<tr>
、<thead>
和 <tfoot>
标签之外但在 <tbody>
标签内部带有 <table>
标签的表将根据 W3C 标记验证服务进行验证。
此文档已成功检查为 HTML 4.01 Transitional:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="en">
<head>
</head>
<body>
<table>
<thead>
<th colspan="2">head1</th>
<th>head2</th>
</thead>
<tfoot>
<th colspan="2">foot1</th>
<th>foot2</th>
</tfoot>
<tr><td colspan="3">this row is outside of thead and tfoot</td></tr>
<tbody>
<tr>
<td>1-1</td>
<td>1-2</td>
<td>1-3</td>
</tr>
<tr>
<td>2-1</td>
<td>2-2</td>
<td>3-3</td>
</tr>
<tr>
<td>3-1</td>
<td>3-2</td>
<td>3-3</td>
</tr>
</tbody>
</body>
</html>
<tbody>
(表格标题)或
<table>
(表格页脚)元素,则
<thead>
用于标记 <tfoot>
的正文。如果您的表格不包含这些元素,您可以不使用 <tbody>
。
正确的用法是:
<table>
<thead><tr><th>Item </th><th>Cost </th></tr></thead>
<tbody><tr><td>Stack Overflow</td><td>Free </td></tr>
<tr><td>Something cool</td><td>$1.00</td></tr></tbody>
</table>
如果
<tr>
位于 <tbody>
之外,则页面将不会验证:
http://validator.w3.org
正如其他人所指出的,
<tbody>
是可选的,除非您使用<thead>
或<tfoot>
。使用后两个元素的主要原因是,如果打印长表格,则页眉和页脚会在每页上重复。
听起来您可能正在创建类似日历的东西,您希望在其中交替出现
<th>
行(例如,对于日期)和 <td>
(例如,对于该日期的事件)。如果是这种情况,您不应该将交替的行包装在 <thead>
和 <tbody>
中 - 这样做会使浏览器在打印页面时感到困惑。如果您只保留分组元素,您的表格就会有效。但是,某些屏幕阅读器可能会对该标记感到困惑,并将最上面一行标题应用于其下方的所有单元格。对于像这样的复杂表格,您需要添加额外的标记以确保屏幕阅读器了解表格的组织方式。这是带有可访问标记的表格:
<table summary="A brief description of how the table is organized, for screen reader users">
<tr>
<th colspan='2' id="header1">...</th>
</tr>
<tr>
<td headers="header1">...</td>
<td headers="header1">...</td>
</tr>
<tr>
<th colspan='2' id="header2">...</th>
</tr>
<tr>
<td headers="header2">...</td>
<td headers="header2">...</td>
</tr>
</table>
或者,您可能需要考虑是否可以将数据组织在多个表中,或者是否可以提供更易于屏幕阅读器用户使用的替代版本。例如,事件日历可以另外呈现为事件列表。