Wrap long word (text) in table cell
Tables in HTML are a quite strange elements. You can set some CSS rules, linke width for columns, and somethimes – nothing happens. This happens especially when in table cell is placed a very long text – the single word (or basically, a long string without spaces).
Here is the live example of this situation, when we have a very long word in table cell and it breaks totally the proportion between columns widths. First and second html table’s column should take 25% of table’s width, third 20%, and the last one – 30%. But this one single word in last column makes it much more longer than 30% of html table width. As the result whole HTML table has wrong column’s widths. Check it below:
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<table> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Details</th> </tr> </thead> <tbody> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> <td> LoremipsumdolorsitametconsecteturadipiscingelitIntegemagnanunc </td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> <td> LoremipsumdolorsitametconsecteturadipiscingelitIntegemagnanunc </td> </tr> </tbody> </table> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
table { width: 100%; border-spacing: 0; border-collapse: collapse; } table td { } table td, table th { border: 1px solid #dadada; padding: 5px; } table thead th { text-align: left; } table thead th:nth-child(0), table thead th:nth-child(1){ width: 25%; } table thead th:nth-child(2){ width: 20%; } table thead th:nth-child(3){ width: 30%; } |
RESULTS:
How to wrap long word (text without spaces) in html table’s cell?
This is very, very easy! We must add only a CSS proprty to table cell “td” tag – “word-break: break-all;” then all column’s widths become as intended. Check it in example below:
CSS
1 2 3 |
td { word-break: break-all; } |
RESULTS:
Is this a right solution in your opinion? Or do you have another problem? Please, write a comment below 🙂