11

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.

Firefox display

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

IE 9 display

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bob
  • 281
  • 1
  • 4
  • 13

2 Answers2

14

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.

Max
  • 12,622
  • 16
  • 73
  • 101
dan
  • 856
  • 9
  • 20
  • Thanks. Adding the doctype declaration solved the problem in IE. – Bob Nov 29 '11 at 03:40
  • I have a new situation now. I cannot turn off the compatibility view in IE as other parts of the page must be viewed in compatibility view. So, is there a way to accomplish the style like in Firefox without turning off the compatibility view in IE9? – Bob Nov 29 '11 at 04:23
  • yep. make sure your code is all nicely validated and well structured. make sure your page gets no errors at http://validator.w3.org/ – dan Nov 29 '11 at 06:44
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>
Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215