如何使列的宽度适合其HTML表中的内容? [英] How to make width of a column fit to its contents in HTML table?

查看:93
本文介绍了如何使列的宽度适合其HTML表中的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML中有以下表格

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>

我希望第二行和第三行中的第一列宽度恰好适合内容长度为什么我把 width =1px有)。在平均而言,我想要表宽度只是适合表中的最长内容的长度(这是第一行),而不是跨越到其边界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.

它在Firefox中可用,如下所示。

It works in Firefox as shown below.

但是,在IE 9中它不能正常工作,如图所示。

However, in IE 9 it does not work as expected, as shown.

我试图用 width =1%替换 width =1px。但是,表宽度将跨越父div的最大宽度。

I tried to replace width="1px" with width="1%". But then the table width will span to the max-width of the parent div.

有没有人知道如何在IE中修复它?

Does anyone know how to fix it in IE?

提前感谢。

推荐答案

我刚刚在我的IE9测试,并将宽度设置为1px作品。但它显示如上所示在兼容模式。您是否已宣布您的doctype和所有其他有趣的东西?

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?

这可能是因为您使用旧的方法来显示表格。您可以尝试在CSS中使用边框等设置表格样式,例如:

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:

table, td, tr, th{
  border:1px solid #f0f;
}

.onepx{
  width:1px;
}



<div style="max-width:700px;">
  <table>
    <tr><td colspan="2">this is a loooooooooooooooong text</td></tr>
    <tr><td class="onepx">a:</td><td>b</td></tr>
    <tr><td class="onepx">c:</td><td>d</td></tr>
  </table>
<div>

等等 - 我相信你的想法。这可能会阻止它在兼容性视图中自动显示(如果是问题)。

and so forth - I am sure you get the idea. this might stop it automagically displaying in compatibility view (if it is the problem).

最后,因为IE9非常笨,所以你必须关闭兼容性视图(如果在页面上启用),因为域中的所有页面都将在兼容性视图中查看。

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.

这篇关于如何使列的宽度适合其HTML表中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆