问题
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.
回答1:
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:
- Loading the data in the table while the
table-layout
is set to auto. - Reading the width of the columns I want to be dynamic.
- Setting those column widths to their current values.
- 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/
回答2:
I discovered this while wrestling with the same problem:
Setting break-word on an element corresponds exactly to inserting a zero-width space between every character of the text contained inside that element.
Except that this actually works with normal, dynamic tables!
This solution is very fast, since it does not require any Javascript.
(It could however be used from Javascript if desired. Find all cells with break-word, grab all the child text nodes, and insert a zero-width space between every character. Even then, the script would run only once during page load, so this should still be extremely performant.)
Zero-width space is ​
回答3:
You can use: word-wrap css style to break the long sentences.
word-wrap: break-word
回答4:
It's easy to handle/wrap long words in DIVs and fixed tables (table-layout:fixed) - just apply CSS3 word-wrap:break-words.
Within dynamic tables above property does only half of the work. We need additionally to help the browsers find break points.
A bit more detailed explanation can be found in the article Wrap long words within dynamic tables.
来源:https://stackoverflow.com/questions/4568035/word-wrapping-a-long-table-cell-while-maintaining-dynamic-widths-in-others