如何使 HTML 表格中的列宽适合其内容?
我的 HTML 中有下表:
<div style="max-width:700px;">
<table border="1">
<tr><td colSpan="2">this is a loooooooooooooooong text</td></tr>
<tr><td width="1px">a:</td><td >b</td></tr>
<tr><td width="1px">c:</td><td >d</td></tr>
</table>
<div>
我希望第二行和第三行中的第一列宽度恰好适合内容长度(这就是我在那里放置 width="1px"
的原因)。与此同时,我希望表格宽度适合表格中最长内容的长度(即第一行),而不是跨越其边界 div 的最大宽度。
它在 Firefox 中的工作原理如下所示。
但是,在 IE 9 中,它无法按预期工作,如图所示。
我尝试将 width="1px"
替换为 width=" 1%”
。但是表格宽度将跨越父 div 的最大宽度。
有谁知道如何在 IE 中修复它吗?
I have the following table in my HTML:
<div style="max-width:700px;">
<table border="1">
<tr><td colSpan="2">this is a loooooooooooooooong text</td></tr>
<tr><td width="1px">a:</td><td >b</td></tr>
<tr><td width="1px">c:</td><td >d</td></tr>
</table>
<div>
I want the first column width in the second and third row to just fit the content length (that is why I put width="1px"
there). In the mean while, I want to table width to just fit the length of the longest content in the table (which is the first row) instead of spanning to the max-width of its bounding div.
It works in Firefox as shown below.
However, in IE 9 it does not work as expected, as shown.
I tried to replace width="1px"
with width="1%"
. But then the table width will span to the max-width of the parent div.
Does anyone know how to fix it in IE?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我刚刚在 IE9 中测试过,将宽度设置为 1px 可以。但它会按照您上面在兼容模式下呈现的方式显示。你声明了你的文档类型和所有其他有趣的东西吗?
这可能是因为您使用旧方法来显示表格。您可以尝试在 CSS 中使用边框等设计表格样式 - 例如:
等等 - 我相信您明白了。这可能会阻止它自动显示在兼容性视图中(如果这是问题)。
最后,由于 IE9 太愚蠢了,您将不得不关闭兼容性视图(如果在页面上启用了它),因为域内的所有页面都将在兼容性视图中查看。
I have just tested in my IE9, and setting the width to 1px works. But it displays as you presented above in compatibility mode. Have you declared your doctype and all other fun stuff?
It might be because you are using older methods to display the table. You could try styling the table with borders and so on in CSS - such as:
and so forth - I am sure you get the idea. this might stop it automagically displaying in compatibility view (if it is the problem).
And finally, because IE9 is so stupid, you will have to turn off the compatibility view (if it is enabled on the page), because all pages within the domain will be viewed in compatibility view.
你提到你曾尝试将其设置为1%,你是否将其他设置为99%?
You mentioned that you have tried setting it to 1%, did you set the other to 99%?