我如何指定一个td标签应该跨越所有列(当表中的列的确切数量将是可变的/难以确定当HTML被呈现)?w3schools提到你可以使用colspan="0",但它没有确切地说什么浏览器支持这个值(IE 6在我们的列表中支持)。

看起来,将colspan设置为大于您可能拥有的理论列数量的值是可行的,但如果您将表布局设置为fixed,则它将不起作用。对colspan使用一个大数字的自动布局有什么缺点吗?有更正确的方法吗?


当前回答

只需将colspan设置为表中的列数。

所有其他的“捷径”都有陷阱。

最好的方法是在开始时将colspan设置为正确的数字。如果您的表有5列,则将其设置为colspan="5",这是在所有场景中都有效的唯一方法。不,这不是一个过时的解决方案,也不是只推荐用于IE6之类的——这实际上是处理这个问题的最佳方式。

我不建议使用Javascript来解决这个问题,除非在运行时列的数量发生了变化。

如果列数是可变的,则需要计算列数,以便填充colspan。如果您的列数是可变的,那么无论生成表的是什么,都应该能够适应于计算表的列数。

正如其他答案所提到的,如果您的表没有设置为table-layout: fixed,您也可以将colspan设置为一个非常大的数字。但我发现这个解决方案很混乱,如果你稍后回来决定它应该是一个固定的表格布局,这可能会让你头疼。最好第一次就做对了。

其他回答

colspan="100%"

它的工作也在电子邮件outlook, gmail....

另一个可行但丑陋的解决方案:colspan="100",其中100是一个大于需要colspan的列总数的值。

根据W3C的规定,colspan="0"选项仅对COLGROUP标记有效。

If you want to make a 'title' cell that spans all columns, as header for your table, you may want to use the caption tag (http://www.w3schools.com/tags/tag_caption.asp / https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) This element is meant for this purpose. It behaves like a div, but doesn't span the entire width of the parent of the table (like a div would do in the same position (don't try this at home!)), instead, it spans the width of the table. There are some cross-browser issues with borders and such (was acceptable for me). Anyways, you can make it look as a cell that spans all columns. Within, you can make rows by adding div-elements. I'm not sure if you can insert it in between tr-elements, but that would be a hack I guess (so not recommended). Another option would be messing around with floating divs, but that is yuck!

Do

<table>
    <caption style="gimme some style!"><!-- Title of table --></caption>
    <thead><!-- ... --></thead>
    <tbody><!-- ... --></tbody>
</table>

<div>
    <div style="float: left;/* extra styling /*"><!-- Title of table --></div>
    <table>
        <thead><!-- ... --></thead>
        <tbody><!-- ... --></tbody>
    </table>
    <div style="clear: both"></div>
</div>

就用这个吧:

colspan="100%"

它适用于Firefox 3.6, IE 7和Opera 11!(我猜在其他人身上,我无法尝试)


警告:正如下面评论中提到的,这实际上与colspan="100"相同。因此,这个解决方案将打破表与css table-layout:固定,或超过100列。

只需将colspan设置为表中的列数。

所有其他的“捷径”都有陷阱。

最好的方法是在开始时将colspan设置为正确的数字。如果您的表有5列,则将其设置为colspan="5",这是在所有场景中都有效的唯一方法。不,这不是一个过时的解决方案,也不是只推荐用于IE6之类的——这实际上是处理这个问题的最佳方式。

我不建议使用Javascript来解决这个问题,除非在运行时列的数量发生了变化。

如果列数是可变的,则需要计算列数,以便填充colspan。如果您的列数是可变的,那么无论生成表的是什么,都应该能够适应于计算表的列数。

正如其他答案所提到的,如果您的表没有设置为table-layout: fixed,您也可以将colspan设置为一个非常大的数字。但我发现这个解决方案很混乱,如果你稍后回来决定它应该是一个固定的表格布局,这可能会让你头疼。最好第一次就做对了。