1

我有一个有两行的表。第二行由 colspan="2" 中的长文本组成。如何包装此文本以使表格不比两个第一行单元格宽?我无法为表格设置固定宽度,因为前两个单元格是动态的。

http://jsfiddle.net/qLpuq/1/

<table>
    <tr>
        <td>Cell 1</td>
        <td>Cell 2</td>
    </tr>
    <tr>
        <td colspan="2" style="width: 0" >Very long cell that should just be as long as the first two cells and wrap, but not take all the screen width.</td>
    </tr>
</table>

我错误地认为,这style="width: 0"将适用于该单元格。

4

3 回答 3

4

恐怕没有直接的解决办法。您可以使用 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>
于 2013-07-10T12:53:18.597 回答
0

将 max-width 与 colspan2 的 % 一起使用

                 <table style="width:100%;" border="1">
    <tr>
        <td style="width: 50%;">Cell 1</td>
        <td style="width: 50%;">Cell 2</td>
    </tr>
    <tr>
        <td colspan="2" style="max-width: ??%;" >Very long cell that should just be as long as the first two cells and wrap, but not take all the screen width.</td>
    </tr>
</table>
于 2013-07-10T12:50:48.377 回答
0

可能对你有用。。

 <table style="width:300px;" border="1">
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
        </tr>
        <tr>
            <td colspan="2" style="width: 70%;" >Very long cell that should just be as long as the first two cells and wrap, but not take all the screen width.</td>
        </tr>
    </table>

问题更新后更新

 <table style="width:100%;" border="1">
        <tr>
            <td style="width: 50%;">Cell 1</td>
            <td style="width: 50%;">Cell 2</td>
        </tr>
        <tr>
            <td colspan="2" style="width: 70%;" >Very long cell that should just be as long as the first two cells and wrap, but not take all the screen width.</td>
        </tr>
    </table>
于 2013-07-10T08:38:01.313 回答