【发布时间】:2019-11-14 14:56:26
【问题描述】:
我有一张这样的 HTML 表格:
table { border-collapse: collapse; }
table thead th:nth-child(1) { width: 180px }
table thead th:nth-child(2) { width: 150px }
table thead th:nth-child(3) { width: 170px }
table thead tr { border-bottom:2px solid #222; }
table tbody tr { border-top:1px solid #ddd; }
table tbody tr:hover { background: #def; }
table tbody td { height: 40px; }
<div>
<table>
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1 1</td>
<td>Content 1 2</td>
<td>Content 1 3</td>
</tr>
<tr>
<td>Content 2 1</td>
<td>Content 2 2<br>Line 2<br>Line 3<br>Line 4</td>
<td>Content 2 3</td>
</tr>
<tr>
<td>Content 3 1</td>
<td>Content 3 2</td>
<td>Content 3 3</td>
</tr>
</tbody>
</table>
</div>
列将具有不同的固定宽度值,在 CSS 中指定,这将定义表格的大小。在上面的示例中,列分别为 180px、150px 和 170px,因此表格将是 500px 宽。
由于设计的原因,我们需要让表格占容器的 100%不调整列的大小。这意味着,例如,如果屏幕为 900 像素,列仍将占用它们的 500 像素,但表格应拉伸到容器的末尾以占用剩余的 400 像素。
将表格宽度设置为 100%,并添加一个自动占据剩余空间的新列将解决此问题。但是我们被要求避免添加这样的列,因为屏幕阅读器会遍历它并将其作为一个空单元格读取,这可能会让用户感到困惑。
一个hacky选项是添加一个占据整个页面宽度的伪元素(包装div有一个overflow: hidden,如下面的演示)。但是这个解决方案的问题是,如果表格的列占据的宽度超过了页面的宽度,我们希望包含的 div 滚动,但是我们会看到看起来像一个巨大的空行。
table { border-collapse: collapse; }
table thead th:nth-child(1),
table thead th:nth-child(1) { min-width: 180px }
table thead th:nth-child(2) { min-width: 150px }
table thead th:nth-child(3) { min-width: 170px }
table thead tr { border-bottom:2px solid #222; }
table tbody tr:not(:first-child) { border-top:1px solid #ddd; }
table tbody tr:hover { background: #def; }
table tbody td { height: 40px; }
div {
overflow: hidden;
}
table tr::after {
content: "";
display: block;
width: 100vw;
}
<div>
<table>
<thead>
<tr>
<th>Heading 1</th>
<th>Heading 2</th>
<th>Heading 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Content 1 1</td>
<td>Content 1 2</td>
<td>Content 1 3</td>
</tr>
<tr>
<td>Content 2 1</td>
<td>Content 2 2<br>Line 2<br>Line 3<br>Line 4</td>
<td>Content 2 3</td>
</tr>
<tr>
<td>Content 3 1</td>
<td>Content 3 2</td>
<td>Content 3 3</td>
</tr>
</tbody>
</table>
</div>
是否有一种可访问的方式让表格占据整个宽度,但列仅占据分配的宽度?
【问题讨论】:
-
你真的需要表格来占据那个空间,还是仅仅需要出现来占据这个空间?
-
@steveax 无论哪种方式都可以,只要列保持在指定的宽度。
标签: html css html-table accessibility