How to make width of a column fit to its contents

2019-04-06 20:32发布

问题:

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?

回答1:

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:

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).

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.



回答2:

You mentioned that you have tried setting it to 1%, did you set the other to 99%?

<tr><td width="1%">a:</td><td width="99%">b</td></tr>
<tr><td width="1%">c:</td><td width="99%">d</td></tr>