Zero-Width HTML Space

Let’s say you have the text “Life insurance/Dependent Life” and you want to fit it into a small space with a small font. If you try it normally, most browsers might break the text so that it looks like:

Life
insurance/Dependent
Life

One solution is to just replace the forward slashes with a forward slash followed by a space giving you “Life insurance/ Dependent Life“. Not the end of the world but not ideal, I’d rather it break at the slashes. That’s where the zero-width space character (U+200B) comes in. You can replace the forward slash with a forward slash followed by and if the browser needs to, it will break at the forward slash, otherwise it will display the slash with no white space around it.

The bad news is that IE6 doesn’t know what to do with that character. The good news is that with a little javascript you can replace that character (and the even better news, after August 22nd hopefully most people will be upgraded to IE8). In my case, only my hyperlinks use this trick so below I’m searching for only <a> tags.


    if (navigator.userAgent.indexOf('MSIE 6.') > 0) {
        var as = document.getElementsByTagName('a');
        var p = /u200b/g;
        for (var i = as.length - 1; i >=0 ; i--) {
            if (p.test(as[i].innerHTML)) {
                as[i].innerHTML = as[i].innerHTML.replace(p, '<wbr/>');
            }
        }
    }

You may notice that I’m walking backwards through the array (and that I don’t like --i), and to be honest I’m not sure why but going forwards didn’t catch all of the occurrences. Also, in case you’re wondering, I use this in my L3 navigation so I don’t have to worry about monkeying with my web.sitemap file figuring exactly how to break things. It does cause a little jump to occur in IE6 because I’m calling the JS onload but that’s okay with me.