Home How To Wrap Text in a Table Cell
Post
Cancel

How To Wrap Text in a Table Cell

An interesting question that came up today during work was how to wrap text in a table cell that does not contain any line breaks or spaces. For example:
ThisIsCell1ThisIsCell2
We want the text inside the cells to wrap to the next line instead of extending the table size. There are three basic solutions: 1. CSS - Internet Explorer Specific. In Internet Explorer, there is a custom CSS extension called "word-wrap" which when set as "word-wrap: break-word;" will do just what we want. For example (only in IE):
ThisIsCell1ThisIsCell2
2. CSS3 (no browsers yet). In CSS 3 a new option called "wrap-option" is defined which when set as "wrap-option: emergency;" will do the same. Unfortunatly no browser today (except maybe Safari) supports it yet. The following example will only work in a CSS 3 browser (none of which I have):
ThisIsCell1ThisIsCell2
3. JavaScript (all browsers). Another solution would be to use JavaScript to break up the text into specific sized chunks. The downside of this approach is that you have to figure out what the chunk size would be. A good example of a JavaScript can be found here. I slightly modified it as follows:
strbuff='ThisIsCell1';
    newstr='';
    startI = 0;
    max=2;
    str='';
    subarr=new Array(parseInt(strbuff.length/max+1));
    for (i=0;i    {
       subarr[i]=strbuff.substr(startI,max);
       startI+=max;
    }
    for (i=0;i    {
       newstr+=subarr[i]+'';
    }
    str+=subarr[subarr.length-1];
    document.write(newstr);
 } else {
 	document.write(strbuff);
 }
There is also a fourth way to do it via XSLT as described in Jeni Tennison's book but I don't have the time to get to that today. I will try to post a followup tomorrow.


UPDATE: Here is the followup post.
This post is licensed under CC BY 4.0 by the author.