I\'ve been using word-wrap: break-word
to wrap text in div
s and span
s. However, it doesn\'t seem to work in table cells. I have a tabl
Turns out there's no good way of doing this. The closest I came is adding "overflow:hidden;" to the div around the table and losing the text.
The real solution seems to be to ditch table though. Using divs and relative positioning I was able to achieve the same effect, minus the legacy of <table>
2015 UPDATE: This is for those like me who want this answer. After 6 years, this works, thanks to all the contributors.
* { // this works for all but td
word-wrap:break-word;
}
table { // this somehow makes it work for td
table-layout:fixed;
width:100%;
}
Tested in IE 8 and Chrome 13.
<table style="table-layout: fixed; width: 100%">
<tr>
<td>
<div style="word-wrap: break-word;">
longtexthere
</div>
</td>
<td><span style="display: inline;">Foo</span></td>
</tr>
</table>
This causes the table to fit the width of the page and each column to take up 50% of the width.
If you prefer the first column to take up more of the page, add a width: 80%
to the td
as in the following example, replacing 80% with the percentage of your choice.
<table style="table-layout: fixed; width: 100%">
<tr>
<td style="width:80%">
<div style="word-wrap: break-word;">
longtexthere
</div>
</td>
<td><span style="display: inline;">Foo</span></td>
</tr>
</table>
A solution which work with Google Chrome and Firefox (not tested with Internet Explorer) is to set display: table-cell
as a block element.
It appears you need to set word-wrap:break-word;
on a block element (div
), with specified (non relative) width. Ex:
<table style="width: 100%;"><tr>
<td><div style="display:block; word-wrap: break-word; width: 40em;">loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</div></td>
<td><span style="display: inline;">Foo</span></td>
</tr></table>
or using word-break:break-all
per Abhishek Simon's suggestion.
The only thing that needs to be done is add width to the <td>
or the <div>
inside the <td>
depending on the layout you want to achieve.
eg:
<table style="width: 100%;" border="1"><tr>
<td><div style="word-wrap: break-word; width: 100px;">looooooooooodasdsdaasdasdasffffdffffdffffdffffdffffdffffdffffdffffdffffdffffdasdasdasdsadng word</div></td>
<td><span style="display: inline;">Foo</span></td>
</tr></table>
or
<table style="width: 100%;" border="1"><tr>
<td width="100" ><div style="word-wrap: break-word; ">looooooooooodasdsdaasdasdasffffdffffdffffdffffdffffdffffdffffdffffdffffdffffdasdasdasdsadng word</div></td>
<td><span style="display: inline;">Foo</span></td>
</tr></table>
If you do not need a table border, apply this:
table{
table-layout:fixed;
border-collapse:collapse;
}
td{
word-wrap: break-word;
}