2008年11月7日星期五

"Zero Width Space" hack for wrapping words in HTML

It's not easy to wrap words in non-IE browsers. IE has its proprietary CSS property : word-wrap. But for other browsers, if the word is too long, the text stretches. This is because that the wrapping happens between the words' boundaries, i.e. white spaces.

A small hack for this is to add "Zero Width Space" between all the characters in the word. By doing this, word wrapping can happen between all the characters, but the users can not see them since the width of the spaces is zero. This can be done by the following small function:

function breakWords(str) {
Array.prototype.slice.apply(str).join("​​");
}

Technology changes life