Monday, September 8, 2014

Word Wrapping inside a table cell

You may have faced situations where you need to place long texts inside a small HTML table cell. You may need to keep the width of the cell fixed and wrap the text so that it breaks at the border of the cell. Everything will work fine as long as all the words in the text are shorter than the cell width. But what happens if you have longer words. Yes the cell will get expanded to display the word in a single line.
How to avoid this behavior and let the word break and span in two or multiple lines. You will first try something like this.

<table border="1" width="40%">
  <tr>
    <td style="width:50px;word-wrap: break-word">Is this extraodinary??????????</td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
</table>

 But this does not work. The whole part "extraodinary??????????" will display in the same line.


How to overcome this behavior? Simple, just make the layout of the table fixed by adding the style "table-layout:fixed" to the table.

<table border="1" width="40%" style="table-layout:fixed;">
  <tr>
    <td style="width:50px;word-wrap: break-word">Is this extraodinary??????????</td>
    <td> </td>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
  </tr>
</table>

Wow... Now it works. Now the output will look like this.


Note:- To be this worked in most browsers you may need to assign a width to the table.

No comments:

Post a Comment