May 2009
M T W T F S S
« Mar   Sep »
 123
45678910
11121314151617
18192021222324
25262728293031

Word wrapping, JavaScript vs CSS

Here’s the scenario:

You have some content that you’re pulling from a database. It’s user-generated, so you have no guarantee that it makes sense. That means that people could fill up all the allowed characters without entering any spaces, insert quotation marks and apostrophes, and anything else. Now, you want to display this data in, say, a table with a fixed width.

We want to make the words wrap. We don’t want to overflow the container, and we’d prefer not to hide the text.

If all your users are using IE, then you’re in luck: use the CSS “word-wrap: break-word” (or if you have a browser from the future, when CSS3 will have this and more). If not, we have to make a choice.

If you absolutely need word wrapping, here is what I’ve come up with. It’s definitely clunky, and I’d love to see a better solution. It does, however, work. I would not recommend using this method on a large string, as the user may see a hit in performance.


<span id="text" style="display: none">your-possibly-really-long-string-goes-here</span>

<script type="text/javascript" language="javascript">
	var string = document.getElementById('text').innerHTML;
	var stringWords = string.split(' ');
	for (var i = 0; i < stringWords.length; i++) {
		if (stringWords[i].length > 20) {
			stringWords[i] = stringWords[i].split('').join('<wbr />');
		}
	}
	string = stringWords.join(' ');
	document.write(string);
</script>

The JavaScript splits the string into words (strings separated by spaces), and then for any word that is longer than 20 characters, it inserts <wbr /> after each character. By limiting this to long words, you won’t be splitting short words in awkward places. The wbr (Word BReak) tag inserts a soft line break. In other words, if the text would overflow the container otherwise, a line break will be inserted. For more useful information and for comparison of wbr, & shy;­, and & #8203;​ see this site.

To make the wbr tag compatible with Opera, you’ll need to add this bit of CSS:

wbr { display: inline-block; }

I tested with Safari 4, Firefox 3.0.10, IE 6, Opera, and Chrome with no problems.

If, however, you do not need word-wrapping, life is much simpler. The CSS property “overflow” is all you need to prevent text from overflowing its container. Put it in a div and give it a bit of CSS. You have several choices, but only two of them matter.

By specifying “overflow: hidden”, all text that would have overflowed the contained is, well, hidden. It’s truncated. Any strings that are ridiculously long probably aren’t valuable, so why not?

The other choice is “overflow: auto”, which will give the div a scroll bar if its contents are trying to over flow it.

If you have a better solution to this problem, please let me know. I’m really looking forward to CSS3.

4 comments to Word wrapping, JavaScript vs CSS