Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make width of a column fit to its contents in HTML table?

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?

like image 863
Bob Avatar asked Nov 29 '11 02:11

Bob


People also ask

How do I make a table fit the contents of a cell?

To adjust table row and column size in Word: Click anywhere in the table. In "Table Tools" click the [Layout] tab > locate the "Cell Size" group and choose from of the following options: To fit the columns to the text (or page margins if cells are empty), click [AutoFit] > select "AutoFit Contents."


1 Answers

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.

like image 173
dan Avatar answered Oct 17 '22 00:10

dan