colspan messes with fixed width table
我想要一个具有1个小列和2个大列的固定宽度表,如下所示:
1 2 3 | |..|....|....| |..|....|....| |..|....|....| |
使用
1 2 | td.small { width: 20% } td.large { width: 40% } |
然后我想像这样添加一个大的colspan = 2的col
1 2 3 | |.......|....| |..|....|....| |..|....|....| |
使用
1 2 3 | td.small { width: 20% } td.large { width: 40% } td.extralarge { width: 60% } /* 20+40=60 */ |
但我一直以:
1 2 3 | |.......|....| |...|...|....| |...|...|....| |
在jsbin上找到了更多图形化示例
**编辑**
抱歉,我错过了一个细节:
我必须使用(或者我认为..?)
1 2 3 4 5 | td { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } |
更新的jsbin在这里找到。
您还可以使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <table> <colgroup> <col class="short" /> <col span="2" class="long" /> </colgroup> <tr> <td>Short</td> <td>Long long long long</td> <td>Long long long long</td> </tr> <tr> <td>Short</td> <td>Long long long long</td> <td>Long long long long</td> </tr> <tr> <td>Short</td> <td>Long long long long</td> <td>Long long long long</td> </tr> </table> |
使用此CSS:
1 2 3 4 5 6 7 8 9 10 | table { width: 100%; } .short { background: lightblue; width: 20% } .long { background: lightgreen; width: 40%; } .multiCells { background: #F3A633; } |
这样,您无需为每个
JSFiddle演示
colgroup MDN文章
更改表格布局:固定为自动
1 2 3 | table { table-layout: auto; } |
在此处找到有效的演示:http://jsbin.com/atohug/2/edit
LinkinTED提供了可行的解决方案,但是该示例并未直接解决OP的问题或说明其起作用的原因。
该示例应如下所示(借用相同的语法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <table> <colgroup> <col class="short" /> <col span="2" class="long" /> </colgroup> <tr> <td colspan=2>Extra long content</td> <td>Long long long long</td> </tr> <tr> <td>Short</td> <td>Long long long long</td> <td>Long long long long</td> </tr> </table> |
OP的问题是,当您使用table-layout时:修复了该表期望在第一行中明确定义每个单元格的宽度的情况,从而不必在将更多内容添加到后续行中的后续单元格时调整列的大小。但是,如果在第一行中使用colspan = 2,则不知道这两个单元格的宽度,因此它默认为它们合并宽度的50%,并且该决定在表的其余部分是固定的。通过使用colgroup并指定每列的宽度,该表可以预先确定列的宽度,您可以在第一行中自由使用colspan = 2(或更多)。
一个警告。 col width =仅支持像素和%。如果需要使用其他宽度单位,请将col与上述样式相关联。
我知道这篇文章真的很老,但也许我的解决方案可以帮助某人。
您可以在顶部进行伪造的行,并通过将每个单元格的高度设置为0来隐藏它。这将有助于固定表格布局来计算所需的单元格大小。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <table> <tr class="hidden-row"> <td>Short</td> <td>Long long long long</td> <td>Long long long long</td> </tr> <tr> <td colspan=2>Extra long content</td> <td>Long long long long</td> </tr> <tr> <td>Short</td> <td>Long long long long</td> <td>Long long long long</td> </tr> |
1 2 3 | tr.hidden-row td { height: 0; } |