How to make width of a column fit to its contents in HTML table?
Solution 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.
Solution 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>
Bob
Updated on May 15, 2020Comments
-
Bob almost 4 years
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"
withwidth="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?
-
dan over 12 yearsthat won't work because that will set it to 99% of 700 pixels.
-
Bob over 12 yearsThanks. Adding the doctype declaration solved the problem in IE.
-
Bob over 12 yearsI 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?
-
dan over 12 yearsyep. make sure your code is all nicely validated and well structured. make sure your page gets no errors at validator.w3.org