Reputation: 15018
I open this post after I looked at this post without success: How to set table column widths to the longest value, excluding header
I want to draw a table, and I want that the width of each column will be compatible to the longest text in this column. For example, if the following values lie in column A: "abc", "abcd", "abcde", the width of column A will be 5 characters long.
I tried:
td {
white-space: nowrap;
overflow: hidden;
}
How can I do it?
Upvotes: 4
Views: 5677
Reputation: 7611
Add this styling to your table and td:
table {
table-layout:fixed;
}
td {
width:1px;
white-space:nowrap;
}
If this doesn't work, make sure that these are the only styling attributes being set to your table and td. This will help you figure out if other styling attributes are causing conflicts ruining the mentioned styling you want to achieve.
On a similar issue happened with me, these styling attributes weren't working with me because I was setting width
attribute to the table with them. When I removed it, everything worked good as expected.
A quote from the original post I got the solution from:
If the text is non wrapping text then you set the cell to
width:1px
and usewhite-space:nowrap
. The text in that column will then determine the width of the cell.It's a technique commonly used for images and captions (without the
white-space:nowrap
) and allows text to wrap at the limits of an image automatically.
Upvotes: 1
Reputation: 2568
I think that's the default behavior of tables. Have made a simple table that just behaves as you want it (refer this JSFiddle). The column width is equal to the longest text in them.
<table>
<thead>
<th>Column A</th>
<th>Column B</th>
</thead>
<tbody>
<tr>
<td>abc</td> <td>abcdefghijklm</td>
</tr>
<tr>
<td>abcdefghijklmno ddsp</td> <td>ab</td>
</tr>
<tr>
<td>ab</td> <td>ab</td>
</tr>
</tbody>
</table>
Not sure if you wanted to ask something else ?
Upvotes: 3
Reputation: 306
Try styling the text to not wrap:
{
white-space: nowrap;
overflow: hidden;
}
And do not set width settings on your table, tr and td elements.
See if that works.
Upvotes: 0