Ok, so you have a beautiful layout. You are letting users insert data (properly validated, of course), and someone posts a raw URL or other text without a space in it. Your layout is, well, borked. You could of course:
- wrap the text in a div and apply an overflow-x:auto and give it an ugly scrollbar
- wrap the text in a div and apply an overflow:hidden, hiding their content, but not disturbing your layout.
- Deal with it until the CSS3 standard is totally accepted in all browsers used by all clients ( word-wrap: break-word ). IE already understands this syntax.
- This technique, inserting <wbr> tags inside the text telling the browser to break mid-word.
Some background information, the <wbr> tab is a little-known html tag that means “The browser may insert a line break here, if necessary.” It’s supported by Firefox, which is important, because IE and Safari support the word-wrap: breakword CSS3 attribute. Getting your content to contain <wbr> tags when the text is quite long require either server side code, or client-side javascript. I’ll go into how to do this with client side javascript.
One big caveat about <wbr>, while it still works, it’s considered deprecated. Your pages may not validate.
Here is a function that accepts an incoming string and begins looping the string. Every 7 characters, it’s adds a <wbr> tag, unless it finds a space character. It starts counting again if it finds a space character, as the browsers will naturally break here.
[javascript]
function wordwrapper(text){
var counter = 0;
var thisChar;
var out =”;
for(var i=0; i < text.length; i++){
counter++;
thisChar = text.charAt(i);
if (thisChar == ‘ ‘){
counter = 0;
}
if (((counter % 7) == 0) && (counter != 0)){
out = out + thisChar + ”;
}
else {
out = out + thisChar;
}
}
return out;
}
[/javascript]
I still suggest using this in conjunction with the style word-wrap: break-word, as that’s more reliable to fully css3 compatible browsers (and IE, which miraculously already supports this!)
The code’s one gotcha (that I know about) is that it may put a <wbr> directly before a space character, where it isn’t needed. If any reader has a code snippet to share that will only insert <wbr>’s in the string if there are no whitespaces before or after the <wbr>, please share in the comment section.