Word-wrapping a long table cell while maintaining dynamic widths in others

Senseful picture Senseful · Dec 31, 2010 · Viewed 7.7k times · Source

I have a table which has a long line in one of its cells. I need the long line to be split so that it doesn't cause the table to be more than 100% wide. I found that by adding table-layout: fixed and word-wrap: word-break, it will wrap the long cell. However, a side effect of using table-layout is that it causes all columns to have the same width.

You can see an example of that here:

http://jsfiddle.net/RYdLd/2/

How can I make the first column's width auto size to fit only its contents? (i.e. In this example, it should be just wide enough to show the 1 and 2 in that column.)

The data in the table will be loaded dynamically, so a solution which hard codes width values is not good because there's no way to know in advance how wide a column should be. My only option is to use a <table>, I can't use a <div> or some other element.

Answer

Senseful picture Senseful · Jan 1, 2011

According to the official specification, when you use a fixed table-layout, the first row's column widths determine the entire table's column widths. If none of them are defined, it will distribute the column widths evenly.

Since there doesn't seem to be any other option, I ended up using the following method:

  1. Loading the data in the table while the table-layout is set to auto.
  2. Reading the width of the columns I want to be dynamic.
  3. Setting those column widths to their current values.
  4. Changing the table-layout to fixed.

Here's an example which isn't perfect (the width gets decreased by a bit):

http://jsfiddle.net/RYdLd/7/