恐怕没有直接的解决办法。您可以使用 JavaScript,创建仅包含第一行的表格副本,获取其宽度,丢弃副本,并使用宽度来设置真实表格的宽度。结合设置table-layout: fixed
,这应该可以处理这种情况。您可以简化该方法,这样您就不会创建表的副本,而是删除第二行,然后再将其添加回来。它变得相当丑陋:
<!doctype html>
<title>Hack</title>
<style>
table { table-layout: fixed }
tr:first-child td { white-space: nowrap }
</style>
<table id=tbl>
<tbody id=tbody>
<tr>
<td id=cell1>Cell 1</td>
<td id=cell2>Cell 2</td>
</tr>
<tr id=row2><td colspan=2>
Very long cell that should just be as long as the first two cells and
wrap, but not take all the screen width.
</table>
<script>
var tbl = document.getElementById('tbl');
var tbody = document.getElementById('tbody');
var row2 = document.getElementById('row2');
var cell1 = document.getElementById('cell1');
var cell2 = document.getElementById('cell2');
tbody.removeChild(row2);
var width = tbl.clientWidth;
var width1 = cell1.clientWidth;
var width2 = cell2.clientWidth;
tbody.appendChild(row2);
cell1.style.width = width1 + 'px';
cell2.style.width = width2 + 'px';
tbl.style.width = width + 'px';
</script>
一个完全不同的想法是使用一种解决方法,其中长文本不在单元格中,而是在位于caption
表格底部的元素中:
<table>
<caption align=bottom style="text-align: left">
Very long cell that should just be as long as the first two cells and
wrap, but not take all the screen width.
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</table>