Monday, January 28, 2008

Zero-width whitespace and what it can do for you...

One of the most common layout problems I see in the web 2.0 space is accounting for the odd shaped content some people post. Long URLs are among the most common nuisance. Take for example:

http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=G12&q=zwsp+zero-width+space&btnG=Search

A long URL like this often overflows its container and is a layout nightmare. Most people's response is to simply set an overflow value, and either hide the remainder, or have a horizontal scrollbar. Neither of these solutions are ideal. Either way you are obscuring content, and I think everyone agrees that, in a web layout, horizontal scrollbars are the devil.

The solution to this problem is Unicode character U+200C. (a.k.a. ​ or &zwsp;) This character achieves the exact opposite of the common non-breaking space ( ). Zero-width space does not render a visible space to the screen, but acts like a space for breaking up text when wrapping. Here is a javascript example of how to use it:


function linkify(text) {
var pre = text.substr(0,text.indexOf("http://"));
var rest = text.substr(text.indexOf("http://"));
var url = rest.split(/\s/,2)[0];
rest = rest.split(/\s/,2)[1];
var link = '<a href="'+url+'">';
link += url.replace(/(\/|\+|=|\-)/g,"$1&#8203;");
return pre+link+'</a>'+((rest)?rest:'');
}


For the URL above, this would render the following html:

http:/​/​www.google.com/​search?hl=​en&client=​firefox-​a&rls=​org.mozilla%3Aen-​US%3Aofficial&hs=​G12&q=​zwsp+​zero-​width+​space&btnG=​Search

Now this link nicely wraps to fit inside its container, and one of your worst layout nightmares is easily solved. I don't think it takes much creativity to figure out the other potential applications for this character.

I cannot tell you what a pain it was to make sure every &, <, and > symbol in this post was properly escaped, so I hope you found this helpful.